/*
 *  Copyright © 2016, 2017, Oracle and/or its affiliates. All rights reserved.
 *  This software is dual-licensed to you under the MIT License (MIT) and
 *  the Universal Permissive License (UPL). See the LICENSE file in the root
 *  directory for license terms. You may choose either license, or both.
 */

import UIKit

class MotionActivatedCameraView: UIViewController, UITextViewDelegate {
    
    @objc var motionActivatedCamera:MotionActivatedCamera?
    
    @IBOutlet var motionActivatedViewOutlet: UIView!
    @IBOutlet weak var idValueOutlet: UILabel!
    @IBOutlet weak var outputTextViewOutlet: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        outputTextViewOutlet.delegate = self
    }
        
    override func viewWillAppear(_ animated:Bool) {
        super.viewWillAppear(animated)
        // TODO: Hide Back navigation button until navigation is fixed
        self.navigationItem.setHidesBackButton(true, animated: true)
        //DispatchQueue(label:"Motion Activated Camera Sample Queue",
        //              qos: .userInitiated).async(execute: {
        do {
            // Should this be created on every load ?
            self.motionActivatedCamera =
                MotionActivatedCamera(callback: self.updateGUI)
            // Returns endpointId
            self.idValueOutlet?.text =
                try self.motionActivatedCamera?.start()
        } catch {
            showError(controller: self,
                      alertTitle: "Motion Activated Camera",
                      message: "Could not start Motion Activated Camera",
                      actionTitle: "Exit",
                      handler: { action in
                        exit(0)
            })
        }
        //})

        self.idValueOutlet?.text =
        motionActivatedCamera?.dcd?.getEndpointId()
    }
    
    override func viewWillDisappear(_ animated:Bool) {
        super.viewWillDisappear(animated)
    }
    
    // Called from AppDelegate, when application exits
    @objc func close() {
        self.motionActivatedCamera?.stop()
    }
    
    @objc func updateGUI(id: String? = nil, text: String? = nil) {
        DispatchQueue.main.async(execute: {
            if let id = id {
                self.idValueOutlet?.text = id
            }
            if let text = text {
                self.outputTextViewOutlet.text = self.outputTextViewOutlet.text! + "\n" + text
                // Force text field to (invisibly) scroll until latest line is at bottom
                let bottom: NSRange =
                    NSMakeRange(self.outputTextViewOutlet.text.count - 10, 1)
                self.outputTextViewOutlet.scrollRangeToVisible((bottom))
            }
        })
    }
}
