//
//  CoachingUIViewController.swift
//  HeiseARKit3
//
//  Created by Gero Gerber on 18.03.20.
//  Copyright © 2020 Gero Gerber. All rights reserved.
//

import ARKit
import RealityKit
import UIKit

class CoachingUIViewController: UIViewController {

	@IBOutlet var arView: ARView!

	override func viewDidAppear(_ animated: Bool) {
		super.viewDidAppear(animated)
		
		guard ARWorldTrackingConfiguration.isSupported else {
            fatalError("ARWorldTrackingConfiguration is not supported on this device!")
        }
		
		let coachingOverlay = ARCoachingOverlayView()
		coachingOverlay.activatesAutomatically = true
		coachingOverlay.goal = .verticalPlane
		coachingOverlay.delegate = self
		coachingOverlay.translatesAutoresizingMaskIntoConstraints = false
		arView.addSubview(coachingOverlay)
		
		NSLayoutConstraint.activate([
			coachingOverlay.topAnchor.constraint(equalTo: arView.topAnchor),
			coachingOverlay.bottomAnchor.constraint(equalTo: arView.bottomAnchor),
			coachingOverlay.leadingAnchor.constraint(equalTo: arView.leadingAnchor),
			coachingOverlay.trailingAnchor.constraint(equalTo: arView.trailingAnchor)
		])
		
		let config = ARWorldTrackingConfiguration()
		config.planeDetection = [.horizontal, .vertical]
		
		arView.session.delegate = self
		arView.session.run(config, options: .resetTracking)
		coachingOverlay.session = arView.session
	}
}

extension CoachingUIViewController: ARCoachingOverlayViewDelegate {
	func coachingOverlayViewDidRequestSessionReset(_ coachingOverlayView: ARCoachingOverlayView) {
		let config = ARWorldTrackingConfiguration()
		config.planeDetection = [.horizontal, .vertical]
		arView.session.run(config, options: .resetTracking)
	}
}

extension CoachingUIViewController: ARSessionDelegate {
	func sessionShouldAttemptRelocalization(_ session: ARSession) -> Bool {
		return true
	}
}
