//
//  BodyTracking3DViewController.swift
//  HeiseARKit3
//
//  Created by Gero Gerber on 05.03.20.
//  Copyright © 2020 Gero Gerber. All rights reserved.
//

import ARKit
import Combine
import RealityKit
import UIKit

class BodyTracking3DViewController: UIViewController {
    
    @IBOutlet var arView: ARView!
    
	var character: BodyTrackedEntity!
	var request: AnyCancellable?
	
	override func viewDidAppear(_ animated: Bool) {
		super.viewDidAppear(animated)
		
		guard ARBodyTrackingConfiguration.isSupported else {
            fatalError("ARBodyTrackingConfiguration is not supported on this device!")
        }
		
		let config = ARBodyTrackingConfiguration()
		config.automaticSkeletonScaleEstimationEnabled = true
		
		request = Entity.loadBodyTrackedAsync(named: "robot.usdz").sink(receiveCompletion: { loadCompletion in
			// Handle Error
			self.request?.cancel()
		}) { value in
			self.character = value
            self.character!.scale = [1.0, 1.0, 1.0]
            self.character!.position = [0.5, 0, 0]
			self.arView.session.run(config, options: .resetTracking)
			self.arView.session.delegate = self
			self.request?.cancel()
		}
    }
}

extension BodyTracking3DViewController: ARSessionDelegate {
	
	func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
		for currentAnchor in anchors {
			guard let currentBodyAnchor = currentAnchor as? ARBodyAnchor else { continue }
			
			let anchorEntity = AnchorEntity(anchor: currentBodyAnchor)
			anchorEntity.addChild(character)
			arView.scene.addAnchor(anchorEntity)
			
			return
		}
	}
}
