//
//  GameView.swift
//  ArkitDoushiQi
//
//  Created by Enzo JOLYS on 27/05/2024.
//

import SwiftUI
import SpriteKit
import DouShouQiModel

struct GameView: View {
    
    var gameScene:GameScene = GameScene(size: CGSize(width: 940, height: 740))

    @State var msg:String = "Msg"
    
    var body: some View {

        VStack(){
            Text(msg)
            SpriteView(scene: gameScene).task {
 
            gameScene.game.addGameStartedListener { board in startGame()}
            gameScene.game.addGameOverListener { board, result, player in gameOver() }
            gameScene.game.addGameChangedListener { game in gameChange() }
            gameScene.game.addBoardChangedListener { board in boardChange() }

            gameScene.game.addMoveChosenCallbacksListener { board, move, player in moveChose(board: board, move: move, player: player) }
            gameScene.game.addInvalidMoveCallbacksListener { board,move,player,bool in invalidMove(board: board, move: move, player:player, bool:bool)}
                
            gameScene.game.addPieceRemovedListener { _,_,piece in removePiece(piece: piece) }
            
            gameScene.game.addPlayerNotifiedListener { board, player in
                print("Player notif : \(player.id) à toi de jouer ")
                msg = "Player notif : \(player.id) à toi de jouer !"
                
                if (player is IAPlayer ){
                    try! await player.chooseMove(in: board, with: gameScene.game.rules)
                }
            }
            
            try! await gameScene.game.start() 
            }
        }
    }
    
    // ------ Listener -------- //
    
    func startGame() { print("Start game !")
        msg = "Start !!"
    }
    func gameOver() { print("Game over !")
        msg = "Game over !!"
    }
    func gameChange() { print("Game change !") }
    func boardChange() {
        print("Board change !")
        gameScene.displayBoard(board: gameScene.game.board)
    }
    
    func moveChose(board:Board,move:Move,player:Player) {
    }
    
    func invalidMove(board:Board,move:Move,player:Player,bool:Bool) {
        
        if (bool){ // Valid
            print("Move valid de \(player.id)")
            print("Move : \(move.description)")
        }
        else { // Invalid
            print("Move invalid de \(player.id)")
            print("Move : \(move.description)")
            gameScene.displayBoard(board: gameScene.game.board)
        }
        print("------------")
    }
    
    func removePiece(piece:Piece){
        print("Remove piece")
        
        if let node = gameScene.pieces[piece.owner]![piece.animal] {
            print("Remove piece from parent")
            node.removeFromParent()
        }
    }
    
    
    // ------------------------- //
    
}

struct GameView_Previews: PreviewProvider {
    static var previews: some View {
        GameView()
    }
}
