//
//  ARKitViewRepresentable.swift
//  DouShouQi_App
//
//  Created by etudiant on 24/06/2024.
//

import SwiftUI
import ARKit
import RealityKit
import DouShouQiModel

class ARKitView: ARView {
    
    required init(frame frameRect: CGRect) {
        super.init(frame: frameRect)
    }
    
    @MainActor required init?(coder decoder: NSCoder) {
        fatalError("init(coder:) not implemented")
    }
    
    convenience init(imageBoard: String = "board", cell_size: Float = 0.1145) {
        self.init(frame: UIScreen.main.bounds)
        do {
            let game = try Game(withRules: ClassicRules(), andPlayer1: HumanPlayer(withName: "Player 1", andId: .player1)!, andPlayer2: HumanPlayer(withName: "Player 2", andId: .player2)!)
            initBoard(withBoard: game.board, andImage: imageBoard)
        } catch {
            print("error")
        }
    }
    
    func applyConfiguration() {
        let conf = ARWorldTrackingConfiguration()
        self.session.run(conf)
    }
    
    func initBoard(withBoard board: Board, andImage image: String) {
        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(1, 1)))
        let arBoard = ARBoard(image: image)
        anchor.addChild(arBoard)
        self.scene.addAnchor(anchor)
    }
    
    func makeUIView(context: Context) -> ARView {
            
        let arView = ARView(frame: .zero)

        // Create a cube model
        let mesh = MeshResource.generateBox(size: 0.1, cornerRadius: 0.005)
        let material = SimpleMaterial(color: .gray, roughness: 0.15, isMetallic: true)
        let model = ModelEntity(mesh: mesh, materials: [material])
        model.transform.translation.y = 0.05

        // Create horizontal plane anchor for the content
        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
        anchor.children.append(model)

        // Add the horizontal plane anchor to the scene
        arView.scene.anchors.append(anchor)

        return arView
            
    }
        
    func updateUIView(_ uiView: ARView, context: Context) {}
}
