//
//  ObjectDetectionViewController.swift
//  HeiseARKit2
//
//  Created by Gero Gerber on 04.09.18.
//  Copyright © 2018 Gero Gerber. All rights reserved.
//

import ARKit
import UIKit

class ObjectDetectionViewController: UIViewController {

    @IBOutlet var sceneView: ARSCNView!
    @IBOutlet var cameraTrackingState: UILabel!
    @IBOutlet var lastDetectedObject: UILabel!
    
    @IBAction func restartSession() {
        startSession()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "3D Object Detection"
        
        startSession()
    }
    
    func startSession() {
        let arObjectURLs = ARObjectSerializer.enumerateARObjects()
        var referenceObjects = Set<ARReferenceObject>()
        
        for currentURL in arObjectURLs {
            let referenceObject = try! ARReferenceObject(archiveURL: currentURL)
            referenceObjects.insert(referenceObject)
        }
        
        let configuration = ARWorldTrackingConfiguration()
        configuration.detectionObjects = referenceObjects
        configuration.planeDetection = .horizontal
        sceneView.scene = SCNScene()
        sceneView.session.run(configuration, options: .resetTracking)
        sceneView.delegate = self
        sceneView.session.delegate = self
        sceneView.debugOptions = [.showFeaturePoints]
        
        lastDetectedObject.text = ""
    }
}

// MARK: ARSessionDelegate

extension ObjectDetectionViewController: ARSessionDelegate {
    func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
        cameraTrackingState.backgroundColor = StateMapper.trackingStateColor(trackingState: camera.trackingState)
        cameraTrackingState.text = "Tracking State: \(StateMapper.trackingStateDescription(trackingState: camera.trackingState))"
    }
}

// MARK: ARSCNViewDelegate

extension ObjectDetectionViewController: ARSCNViewDelegate {
    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        if let objectAnchor = anchor as? ARObjectAnchor {
            lastDetectedObject.text = objectAnchor.referenceObject.name
            let extent = objectAnchor.referenceObject.extent
            let boundingBox = BoundingBox.createBoundingBoxNode(size: extent, transparency: 0.3)
            return boundingBox
        }
        return nil
    }
}

