//
//  SpriteMeeple.swift
//  DouShouQi_App
//
//  Created by Nathan Verdier on 27/05/2024.
//

import Foundation
import SpriteKit

class SpriteMeeple : SKNode {
    
    static let offset = CGPoint(x: 0, y: 0)
    static let direction = CGVector(dx: 100, dy: 100)
    
    let imageNode : SKSpriteNode
    var ellipseNode : SKShapeNode
    
    var cellPosition: CGPoint{
        didSet(cellPosition){
            self.position.x = SpriteMeeple.offset.x + SpriteMeeple.direction.dx*cellPosition.x
            self.position.y = SpriteMeeple.offset.y + SpriteMeeple.direction.dx*cellPosition.y
        }
    }
    
    init(imageNamed imageName: String, size: CGSize, backgroundColor: UIColor, imageRotation : Double = 0){
        imageNode = SKSpriteNode(imageNamed: imageName)
        imageNode.size = CGSize(width: 90, height: 90)
        
        ellipseNode = SKShapeNode(ellipseOf: CGSize(width: 90, height: 90))
        ellipseNode.fillColor = backgroundColor
        
        cellPosition = CGPoint(x: 0, y: 0)
        
        super.init()
        
        let radians = CGFloat(imageRotation * Double.pi / 180.0)
        imageNode.zRotation = radians
        
        //ellipseNode = SKShapeNode(ellipseOf: CGSize(width: imageNode.size.width, height: imageNode.size.height))
        self.addChild(ellipseNode)
        self.addChild(imageNode)
    }
    
    required init?(coder aDecoder:NSCoder){
        imageNode = SKSpriteNode(imageNamed: "rat")
        ellipseNode = SKShapeNode(ellipseOf: CGSize(width: 100, height: 100))
        cellPosition = CGPoint(x: 0, y: 0)
        super.init(coder: aDecoder)
    }
                                   
    override var isUserInteractionEnabled: Bool{
        set { }
        get { true }
    }
                                   
   override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
    }
   
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let parent = parent, let position = touches.first?.location(in: parent) {
            // Arrondir à la case la plus proche pour x et y
            let x = round(position.x / 100) * 100
            let y = round(position.y / 100) * 100

            // Assurer que les coordonnées sont dans les limites
            let clampedX = min(max(x, -300), 300)
            let clampedY = min(max(y, -400), 400)

            self.position = CGPoint(x: clampedX, y: clampedY)
        }
    }

    
   override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?){
            self.position = touches.first?.location(in: parent!) ?? CGPoint(x: 0, y: 0)
    }
}
