//
//  ArKitView.swift
//  ArkitDoushiQi
//
//  Created by Enzo JOLYS on 12/06/2024.
//

import DouShouQiModel
import Foundation
import ARKit
import RealityKit
import UIKit

class ArKitView : ARView {
    
    
    required init(frame frameRect: CGRect) {
        super.init(frame: frameRect)
    }
        
    required init?(coder decoder: NSCoder) {
        fatalError("init(coder:) not implemented")
    }
    
    convenience init() {
        self.init(frame: UIScreen.main.bounds)
    }
    
    func applyConfiguration() {
        let configuration = ARWorldTrackingConfiguration()
        session.run(configuration)
    }
    
    func defineAnchors() -> AnchorEntity {
        let anchor = AnchorEntity(.plane(.horizontal, classification: .any, minimumBounds: SIMD2<Float>(0.2, 0.2)))
        scene.addAnchor(anchor)
        return anchor
    }
    
    func addGesture(_ pieces:[Owner : [ Animal : Entity?]]){
        for piece in pieces.flatMap({ animal,values in return values })
        {
            if piece.self.value != nil {
                self.installGestures([.all], for: piece.self.value as! Entity & HasCollision).forEach { gestureRecognizer in
                            gestureRecognizer.addTarget(self, action: #selector(handleGesture(_:)))
                        }
            }
        }
            
    }
    
    var initialTransform: Transform = Transform()

    @objc private func handleGesture(_ recognizer: UIGestureRecognizer) {
        guard let translationGesture = recognizer as? EntityTranslationGestureRecognizer, let entity = translationGesture.entity else { return }
            
            switch translationGesture.state {
            case .began:
                self.initialTransform = entity.transform
            case .ended:
                entity.move(to: initialTransform, relativeTo: entity.parent, duration: 1)
            default:
                break
            }
    }
}
