//
//  GraphicButton.swift
//
//  Copyright © 2020 Apple Inc. All rights reserved.
//


import SpriteKit
import SPCScene

open class GraphicButton : Graphic {
    var disabled: SKTexture? = nil
    var selected: SKTexture? = nil
    var base: SKTexture
    
    public var action: (()->Void)?
    
    public var enabled: Bool = true {
        didSet {
            self.texture = enabled ? base : disabled
        }
    }
    
    public init(images: (Image, Image?, Image?), name: String, completion: (()->Void)? = nil) {
        base = SKTexture(image: images.0.uiImage)
        super.init(image: images.0, name: name)
        
        
        isUserInteractionEnabled = true
        if let selectedImage = images.1 {
            selected = SKTexture(image: selectedImage.uiImage)
        }
        if let disabledImage = images.2 {
            disabled = SKTexture(image: disabledImage.uiImage)
        }
        action = completion
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UIResponder
    
    public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        guard enabled else { return }
        if let sel = selected {
            texture = sel
        }
    }
    
    public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        // Strange, but a standard click calls "cancel" instead of "ended"
        // if you merely tap it.
        // This is why the cancelled and ended calls look the same
        super.touchesCancelled(touches, with: event)
        guard enabled else { return }
        texture = base
        DispatchQueue.main.async {
            self.action?()
        }
    }
    
    public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        guard enabled else { return }
        texture = base
        DispatchQueue.main.async {
            self.action?()
        }
    }
    
    
    
    
}
