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

import SwiftUI
import SpriteKit
import DouShouQiModel

struct GameView: View {
    var player1Name: String
    var player1Image: UIImage
    var player2Name: String
    var player2Image: UIImage

    var gameScene: GameScene {
        let scene = GameScene(size: CGSize(width: 940, height: 740),
                              player1Name: player1Name,
                              player1Image: player1Image,
                              player2Name: player2Name,
                              player2Image: player2Image)
        return scene
    }

    @State var msg: String = ""

    var body: some View {
        ZStack {
            Text(msg)
            SpriteView(scene: gameScene)
                .edgesIgnoringSafeArea(.all)
                .task {
                    gameScene.game.addGameStartedListener { board in startGame() }
                    gameScene.game.addGameOverListener { board, result, player in gameOver(result : result) }
                    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()
                }

            VStack {
                HStack {
                    VStack {
                        Image(uiImage: player1Image)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 125, height: 125)
                            .clipShape(Circle())
                            .overlay(Circle().stroke(Color.red, lineWidth: 2))

                        Text(player1Name)
                            .font(.headline)
                            .foregroundColor(.white)
                    }
                    Spacer()
                    VStack {
                        Image(uiImage: player2Image)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 125, height: 125)
                            .clipShape(Circle())
                            .overlay(Circle().stroke(Color.blue, lineWidth: 2))

                        Text(player2Name)
                            .font(.headline)
                            .foregroundColor(.white)
                    }
                }
                .padding()
                Spacer()
                Text(msg)
                    .font(.title)
                    .foregroundColor(.white)
                    .padding()
            }
        }
    }

    // ------ Listener -------- //

    func startGame() {
        print("Start game !")
        msg = "Start !!"
    }

    func gameOver(result : Result) { print("Game over !")
        msg = "Game over ! "
        switch result
        {
        case .winner(let winner, _):
            switch winner {
            case .player1:
                msg = msg + "player 1 wins !"
            case .player2:
                msg = msg + "player 2 wins !"
            default:
                msg = msg + "equality !"
            }
        default:
            msg="Game over !"
        }
        
        gameScene.isGameOver = true
        actionEndGame(scene: gameScene,message: msg)
    }

    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 {
            print("Move valid de \(player.id)")
            print("Move : \(move.description)")
        } else {
            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] {
            actionRemove(size: gameScene.size, node: node, scene: gameScene)
            print("Remove piece from parent")
        }
    }

    // ------------------------- //
}

struct GameView_Previews: PreviewProvider {
    static var previews: some View {
        GameView(
            player1Name: "Player 1",
            player1Image: UIImage(named: "profil")!,
            player2Name: "Player 2",
            player2Image: UIImage(named: "profil")!
        )
    }
}
