//
//  MySwiftUIView.swift
//  SwiftARKit
//
//  Created by Pierre FERREIRA on 11/06/2024.
//

import SwiftUI
import ARKit
import RealityKit


class MyARView : ARView{
    required init (frame frameRect : CGRect){
        super.init(frame: frameRect)
    }
    
    required init?(coder decoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    convenience init() {
        self.init(frame: UIScreen.main.bounds)
        addBoardToTheFloor()
        addMeepleToBoard()
    }
    
    
    
    ///Repère où attacher le plan
    func applyRunConfiguration(){
        //ARWorldTrackingConfiguration.self
        let conf = ARWorldTrackingConfiguration()
        //conf.planeDetection = .horizontal
        session.run(conf)
    }
    
    func defineAnchors() {
        let anchor = AnchorEntity(world: .zero)
        scene.addAnchor(anchor)
    }

    func addBoardToTheFloor() {
        //let configuration = ARWorldTrackingConfiguration()
        //session.run(configuration)
        
        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
        scene.addAnchor(anchor)
        
        let board = try? Entity.load(named: "board")
        if let board {
            anchor.addChild(board)
        }
    }
    
    func addMeepleToBoard(){ //boardAnchor : AnchorEntity
        //let configuration = ARWorldTrackingConfiguration()
        //session.run(configuration)
        
        let objectsName = [ "rat", "cat", "dog", "wolf", "leopard", "tiger", "lion", "elephant"]
        var iterator : Int = 0

        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.3, 0.3))) //Une anchor par case ou une pour tout le plateau ?
        scene.addAnchor(anchor)
        
        /// TODO : Lier au model ?
        for row in 0...7{
            for col in 0...7{
                if (col % 2 == row % 2 ){
                    let meeple = try? Entity.load(named: objectsName[iterator % 7]) //miteux
                    iterator += 1
                    if let meeple {
                        
                        meeple.position.x += 0.1145 * Float(row)
                        meeple.position.y += 0.1145 * Float(col)

                        anchor.addChild(meeple)
                    }
                }
            }
        }
    }
    
//    func createAnchor(){
//        let anchor : AnchorEntity = AnchorEntity(world: .zero)
//        self.scene.addAnchor(anchor)
//
//        let mesh = MeshResource.generateBox(size: 10)
//        let material = SimpleMaterial(color: .red, isMetallic: true)
//        let model = ModelEntity(mesh: mesh, materials: [material])
//        model.transform.translation.y = 0.05
//
//        anchor.addChild(model)
//
////        let tv = try? Entity.load(named: "Data")
////        anchor.addChild(tv!)
//
//    }
}
