//
//  BodyTracking2DViewController.swift
//  HeiseARKit3
//
//  Created by Gero Gerber on 15.03.20.
//  Copyright © 2020 Gero Gerber. All rights reserved.
//

import ARKit
import RealityKit
import UIKit

class BodyTracking2DViewController: UIViewController {

    @IBOutlet var arView: ARView!
    
	var jointViews = [ARSkeleton.JointName: UIView]()
	
	override func viewDidAppear(_ animated: Bool) {
		super.viewDidAppear(animated)
		
		guard ARWorldTrackingConfiguration.isSupported, ARWorldTrackingConfiguration.supportsFrameSemantics(.bodyDetection) else {
            fatalError("ARWorldTrackingConfiguration with Frame-Semantics .bodyDetection is not supported on this device!")
        }
		
		let config = ARWorldTrackingConfiguration()
		config.frameSemantics = .bodyDetection
		
		arView.session.run(config, options: .resetTracking)
		arView.session.delegate = self
		
		addJointView(joint: ARSkeleton.JointName.head)
		addJointView(joint: ARSkeleton.JointName.leftFoot)
		addJointView(joint: ARSkeleton.JointName.leftHand)
		addJointView(joint: ARSkeleton.JointName.leftShoulder)
		addJointView(joint: ARSkeleton.JointName.rightFoot)
		addJointView(joint: ARSkeleton.JointName.rightHand)
		addJointView(joint: ARSkeleton.JointName.rightShoulder)
		addJointView(joint: ARSkeleton.JointName.root)
    }
	
	private func addJointView(joint: ARSkeleton.JointName) {
        let size: CGFloat = 20
		let view = UIView(frame: CGRect(x: 0, y: 0, width: size, height: size))
        view.layer.cornerRadius = size / 2
        view.layer.borderColor = UIColor.blue.cgColor
        view.layer.borderWidth = size / 5
		view.backgroundColor = .green
		jointViews[joint] = view
		self.view.addSubview(view)
	}
}

extension BodyTracking2DViewController: ARSessionDelegate {
	
	func session(_ session: ARSession, didUpdate frame: ARFrame) {
		jointViews.forEach { (key, value) in
			value.isHidden = true
		}
		
		guard let detectedBody = frame.detectedBody else { return }
		
		for currentJoint in jointViews {
			guard let landmarkPos = detectedBody.skeleton.landmark(for: currentJoint.key) else { continue }
			guard !landmarkPos.x.isNaN && !landmarkPos.y.isNaN else { continue }
			applyPositionToView(position: landmarkPos, view: currentJoint.value)
		}
	}
	
	private func applyPositionToView(position: simd_float2, view: UIView) {
		view.isHidden = false
		view.center = CGPoint(x: CGFloat(position.x) * self.view.bounds.width, y: CGFloat(position.y) * self.view.bounds.height)
	}
}
