//
//  SpriteMeeple.swift
//  DouShouQiIOS
//
//  Created by Pierre FERREIRA on 24/05/2024.
//

import Foundation
import SpriteKit
import SwiftUI

/// SpriteMeeple
/// Cette classe est utilisée pour gérer les pièces des joueurs
class SpriteMeeple : SKNode, ObservableObject{
    
    
    let imageNode : SKSpriteNode
    let ellipseNode : SKShapeNode
    
    var cellPosition : CGPoint{
        didSet(oldCellPos){
            self.position.x = SpriteMeeple.offset.x + SpriteMeeple.direction.dx * cellPosition.x;
            self.position.y = SpriteMeeple.offset.y + SpriteMeeple.direction.dy * cellPosition.y;

        }
    }
    
    static let offset = CGPoint(x:-400, y:-300)
    static let direction = CGVector(dx:100, dy:100);
    
    
    //@Published var observers : [ any ObservableObject ] = []
    @Published var observers : [ (SpriteMeeple, Int, Int, Int, Int) async ->() ] = []

    
    public init(imageName imgN : String,size meepleSize : CGSize,color meepleColor : Color){
        imageNode = SKSpriteNode(imageNamed: imgN)
        imageNode.size = meepleSize;
        
        //ellipseNode = SKShapeNode(ellipseOf: imgN,  size: CGSize(width: 100, height: 100))
        ellipseNode = SKShapeNode(ellipseOf: CGSize(width: 100, height: 100))

        ellipseNode.fillColor = UIColor(meepleColor);
        
        
        self.cellPosition = CGPoint(x: 0, y: 0)
        
        super.init()
        
        self.addChild(ellipseNode)
        self.addChild(imageNode)
        
    }
    
    override var isUserInteractionEnabled: Bool{
        set {}
        get {true}
    }
    
    ///TouchesBegan
    /// Cette fonction est appelée lorsque l'utilisateur commence à toucher l'écran
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.position = touches.first?.location(in: parent!) ?? CGPoint(x: 0, y: 0)
    }
    
    ///TouchesEnded
    /// Cette fonction est appelée lorsque l'utilisateur a terminé de toucher l'écran
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

        //* Contantes
        ///Limites du board
        static let rightLimit: CGFloat = 400
        static let leftLimit: CGFloat = -400
        static let topLimit: CGFloat = 300
        static let bottomLimit: CGFloat = -300
        static let gridSize: CGFloat = 100

        /// Bordures du board
        ///Right
        if (self.position.x < leftLimit){
            self.position.x = leftLimit;
        }
        
        ///Left
        if (self.position.x > rightLimit){
            self.position.x = rightLimit;
        }
        
        ///Bottom
        if (self.position.y < bottomLimit){
            self.position.y = bottomLimit;
        }
        
        ///Top
        if (self.position.y > topLimit){
            self.position.y = topLimit;
        }

        if (!Int(self.position.x).isMultiple(of: gridSize)){
            let calcx = self.position.x/gridSize;
            self.position.x = (calcx.rounded(.toNearestOrAwayFromZero))*gridSize;
        }
    
        if (!Int(self.position.y).isMultiple(of: gridSize)){
            let calcy = self.position.y/gridSize;
            self.position.y = (calcy.rounded(.toNearestOrAwayFromZero))*gridSize;
        }
        
        ///Envoi aux observers d'une notif
        
        ///* Execution des Observeurs
        Task {
            for observer in observers {
                await observer(self, Int(cellPosition.x), Int(cellPosition.y), Int(position.x), Int(position.y))
            }
        }
    }
            
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
