//
//  ButtonNode.swift
//  GoldWars
//
//  Created by Niko Jochim on 01.05.20.
//  Copyright © 2020 SP2. All rights reserved.
//

import Foundation
import SpriteKit

class ButtonNode : SKSpriteNode {

    var isEnabled:Bool{
        didSet{
            if isEnabled {
                self.alpha = 1
                self.childNode(withName: "label")?.alpha = 1
            } else {
                self.alpha = 0.3
                self.childNode(withName: "label")?.alpha = 0.3
             }
        }
    }

    let onButtonPress: () -> ()
  
    init(iconName: String, text: String,isEnabled:Bool, position: CGPoint, onButtonPress: @escaping () -> ()) {
        self.onButtonPress = onButtonPress
        self.isEnabled = isEnabled
        let texture = SKTexture(imageNamed: "yellow_button04")
        super.init(texture: texture, color: SKColor.white, size: texture.size())
        self.position = position

        let label = SKLabelNode(fontNamed: "Courier-Bold")

        label.fontSize = 30
        label.fontColor = SKColor.black

        label.zPosition = 1
        label.verticalAlignmentMode = .center
        label.text = text
        label.name = "label"

        if !iconName.isEmpty {
            label.position = CGPoint(x: size.width * 0.25, y: 0)
            let icon = SKSpriteNode(imageNamed: iconName)
            icon.position = CGPoint(x: -size.width * 0.25, y: 0)
            icon.zPosition = 1
            self.addChild(icon)
        } else {
            label.position = CGPoint(x: 0, y: 0)
        }
        self.addChild(label)
        isUserInteractionEnabled = true
  }
  
  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    if isEnabled {
        let action = SKAction.sequence(
            [
                SKAction.scale(by: (3/4), duration: 0.3),
                SKAction.scale(by: (4/3), duration: 0.3),
        ])

        self.childNode(withName: "label")?.run(action)
        self.run(action)
        onButtonPress()
    }

  }


  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

}
