//
//  ImageTrackingViewController.swift
//  HeiseARKit2
//
//  Created by Gero Gerber on 10.09.18.
//  Copyright © 2018 Gero Gerber. All rights reserved.
//

import ARKit
import UIKit

class ImageTrackingViewController: UIViewController {

    @IBOutlet var lastImageDetected: UILabel!
    @IBOutlet var cameraTrackingState: UILabel!
    @IBOutlet var sceneView: ARSCNView!
    
    var referenceImages: Set<ARReferenceImage>!
    
    @IBAction func addReferenceImage() {
        let picker = UIImagePickerController()
        picker.allowsEditing = true
        picker.delegate = self
        present(picker, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        DispatchQueue.global().async { [weak self] in
            self?.referenceImages = ARReferenceImage.referenceImages(inGroupNamed: "AR Resources", bundle: nil)
                
            DispatchQueue.main.async { [weak self] in
                self?.startSession()
            }
        }
    }
    
    func startSession() {
        let configuration = ARImageTrackingConfiguration()
        configuration.trackingImages = referenceImages
        configuration.maximumNumberOfTrackedImages = 10
        
        sceneView.session.run(configuration)
        sceneView.session.delegate = self
        sceneView.delegate = self
    }
}

// MARK: ARSessionDelegate

extension ImageTrackingViewController: 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 ImageTrackingViewController: ARSCNViewDelegate {
    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        if let imageAnchor = anchor as? ARImageAnchor {
            let size = imageAnchor.referenceImage.physicalSize
            let node = BoundingBox.createBoundingBoxNode(size: simd_float3(Float(size.width), 0, Float(size.height)), transparency: 0.3, color: .blue)
            node.position = SCNVector3Make(imageAnchor.transform.columns.3.x, imageAnchor.transform.columns.3.y, imageAnchor.transform.columns.3.z)
            let name = imageAnchor.referenceImage.name ?? ""
            
            DispatchQueue.main.async { [weak self] in
                self?.lastImageDetected.text = "Last Detected Image: \(name)"
            }
            
            return node
        }
        return nil
    }
}

// MARK: UIImagePickerControllerDelegate

extension ImageTrackingViewController: UIImagePickerControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else { return }
        dismiss(animated: true)
        
        let ac = UIAlertController(title: "Question", message: "Please enter image data", preferredStyle: .alert)
        ac.addTextField() { textField in
            textField.placeholder = "Enter name"
        }
        ac.addTextField(){ textField in
            textField.placeholder = "Enter width in centimeters"
        }
        ac.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] _ in
            if let strongSelf = self {
                if let widthCentimeters = Float(ac.textFields![1].text ?? "") {
                    let name = ac.textFields![0].text ?? "No Name"
                    let orientation = CGImagePropertyOrientation(image.imageOrientation)
                    let widthMeters = CGFloat(widthCentimeters / 100.0)
                    let newReferenceImage = ARReferenceImage(image.cgImage!, orientation: orientation, physicalWidth: widthMeters)
                    newReferenceImage.name = name
                    strongSelf.referenceImages.insert(newReferenceImage)
                    
                    DispatchQueue.main.async { [weak self] in
                        self?.startSession()
                    }
                }
            }
        })
        ac.addAction(UIAlertAction(title: "Cancel", style: .default))
        present(ac, animated: true)
    }
}

// MARK: UINavigationControllerDelegate

extension ImageTrackingViewController: UINavigationControllerDelegate {
    
}
