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

import Foundation
import SpriteKit
import SwiftUI

class SpriteMeeple : SKNode{
    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);
    
    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}
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.position = touches.first?.location(in: parent!) ?? CGPoint(x: 0, y: 0)
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        /// Bordures du board
        ///Right
        if (self.position.x < -400){
            self.position.x = -400;
        }
        
        ///Left
        if (self.position.x > 400){
            self.position.x = 400;
        }
        
        ///Bottom
        if (self.position.y < -300){
            self.position.y = -300;
        }
        
        ///Top
        if (self.position.y > 300){
            self.position.y = 300;
        }

        if (!Int(self.position.x).isMultiple(of: 100)){
            let calcx = self.position.x/100.0;
            self.position.x = (calcx.rounded(.toNearestOrAwayFromZero))*100;
        }
    
        if (!Int(self.position.y).isMultiple(of: 100)){
            let calcy = self.position.y/100.0;
            self.position.y = (calcy.rounded(.toNearestOrAwayFromZero))*100;
        }
        
        
    }
            
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
