//
//  BurnGainViewController.swift
//  NeoSpectraMicroSwift
//
//  Created by Si-Ware on 11/13/17.
//  Copyright © 2017 siware. All rights reserved.
//

import UIKit

class BurnGainViewController: UIViewController , NSBluetoothManagerDelegate{
    
    
    @IBOutlet weak var textLabel: UILabel!
    
    //MARK: - View Properties
    var doubledata: [Double] = [Double]()
    var floatdata: [Float] = [Float]()
    var sender = AppDelegate.MainViews.BURNGAIN
    var skipBoardError = 0
    var Iteration = 1
    var loadingActivityIndicator: UIActivityIndicatorView!
    var viewActivityIndicator: UIView!
    var loading = false
    
    func didConnectPeripheral(deviceName aName: String) {
    
    }
    
    func didDisconnectPeripheral() {
        let alertController = UIAlertController(title: "Error", message:
            "Connection Lost.", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
        DispatchQueue.main.async {
            self.skipBoardError = 0
            self.Iteration = 1
            if(self.loading){
                self.removeLoading()
                self.present(alertController, animated: true, completion: nil)
            }
            
        }
    }
    
    func receivedDoubleData(allData: [Double], sender: AppDelegate.MainViews) {
        self.floatdata = []
        self.doubledata = allData
        if self.doubledata.count == 1 {
            DispatchQueue.main.async {
                //if(self.skipBoardError > 0){
                //    self.skipBoardError = 0
                //}
                if(self.Iteration == 1){
                    self.Iteration = 2
                    self.runBurnGain()
                }else{
                    self.Iteration = 1
                    self.removeLoading()
                    self.textLabel.text = "Gain settings stored in DVK successfully"
                    self.textLabel.sizeToFit()
                    self.textLabel.center = self.view.center
                    self.textLabel.isHidden = false
                }
                
            }
        }
    }
    
    func receivedFloatData(allData: [Float], sender: AppDelegate.MainViews) {
        
    }
    
    func reportError(error: UInt8, sender: AppDelegate.MainViews) {
        if(self.skipBoardError < 3){
            //let delayInSeconds = 2.0
            //DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
            DispatchQueue.main.async {
                self.skipBoardError += 1
                print(self.skipBoardError)
                self.Iteration = 1
                self.runBurnGain()
            }
        }else{
            let alertController = UIAlertController(title: "Error", message:
                self.getErrorMessage(error: error), preferredStyle: UIAlertControllerStyle.alert)
            alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
            let delayInSeconds = 2.0
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
                //DispatchQueue.main.async {
                if(self.skipBoardError > 0){
                    self.skipBoardError = 0
                }
                self.Iteration = 1
                if(self.loading)
                {
                    self.removeLoading()
                    self.textLabel.isHidden = false
                }
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }
    
    func getErrorMessage(error:UInt8) -> String
    {
        if(error == 101){
            return "Timeout!"
        }else if(error == 102){
            return "No background!"
        }else{
            return String(format: "Error number: %d" , error)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if(AppDelegate.bluetoothManager != nil && Constants.BlueToothConnected == true){
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.burnGainDelegate = self
            
            //scanning view
            let width: CGFloat = 200.0
            let height: CGFloat = 50.0
            let x = self.view.frame.width/2.0 - width/2.0
            let y = self.view.frame.height/2.0 - height/2.0
            
            self.viewActivityIndicator = UIView(frame: CGRect(x: x, y: y, width: width, height: height))
            self.viewActivityIndicator.backgroundColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 0.7)
            self.viewActivityIndicator.layer.cornerRadius = 10
            
            self.loadingActivityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
            self.loadingActivityIndicator.color = UIColor.white
            self.loadingActivityIndicator.hidesWhenStopped = false
            
            let titleLabel = UILabel(frame: CGRect(x: 60, y: 0, width: 200, height: 50))
            titleLabel.text = "Scanning..."
            titleLabel.textColor = UIColor.white
            
            self.viewActivityIndicator.addSubview(self.loadingActivityIndicator)
            self.viewActivityIndicator.addSubview(titleLabel)
            
            self.textLabel.isHidden = true
            
            let alertController = UIAlertController(title: "Confirm", message:
                "Start storing gain settings in DVK ?", preferredStyle: UIAlertControllerStyle.alert)
            
            alertController.addAction(UIAlertAction(title: "Proceed", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
                self.runBurnGain()
            }))
            
            alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
                self.textLabel.isHidden = false
            }))
            
            DispatchQueue.main.async {
                self.present(alertController, animated: true, completion: nil)
            }
        }else {
            self.textLabel.text = "No NeoSpectraMicro Kit is Connected"
            self.textLabel.sizeToFit()
            self.textLabel.center = self.view.center
            self.textLabel.isHidden = false
        }
    }

    func runBurnGain(){
        if(AppDelegate.bluetoothManager != nil && Constants.BlueToothConnected == true){
            if(self.Iteration == 1){
                if(self.loading == false){
                    self.addLoading()
                }
                let data = Data(bytes: self.setOpticalGainBytes())
                AppDelegate.bluetoothManager?.send(data: data, sender: self.sender)
            }else{
                AppDelegate.bluetoothManager?.send(data: Constants.BURN_GAIN_COMMAND , sender: self.sender)
            }
        }
    }
    
    func setOpticalGainBytes() -> [UInt8]
    {
        //append Command
        var bytes = [UInt8]()
        bytes.append(UInt8(27))
        
        //append Optical Settings Value
        let selectedOption = UserDefaults.standard.string(forKey: "Optical_gain_settings_title")
        if(selectedOption != nil){
            if(UserDefaults.standard.object(forKey: "Optical_gain_settings_options") != nil){
                let kitID = Constants.SelectedDeviceName.components(separatedBy: "_")[1]
                let currentOptions = UserDefaults.standard.object(forKey: "Optical_gain_settings_options") as! [String : String]
                var selectedValue = ""
                if(selectedOption == "Default"){
                    selectedValue = currentOptions[selectedOption!]!
                }else{
                    selectedValue = currentOptions[selectedOption! + "_" + kitID]!
                }
                let value = UInt16(selectedValue)
                let Valuebytes = self.toByteArray(value)
                bytes.append(Valuebytes[0])
                bytes.append(Valuebytes[1])
            }else{
                bytes.append(UInt8(0))
                bytes.append(UInt8(0))
            }
        }else{
            bytes.append(UInt8(0))
            bytes.append(UInt8(0))
        }
        
        return bytes
    }
    
    func toByteArray<T>(_ value: T) -> [UInt8] {
        var value = value
        return withUnsafePointer(to: &value) {
            $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<T>.size) {
                Array(UnsafeBufferPointer(start: $0, count: MemoryLayout<T>.size))
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    //MARK: ViewLoading
    func removeLoading() -> Void {
        loading = false
        self.loadingActivityIndicator.stopAnimating()
        UIApplication.shared.endIgnoringInteractionEvents()
        self.viewActivityIndicator.removeFromSuperview()
    }
    
    func addLoading() -> Void {
        self.view.addSubview(self.viewActivityIndicator)
        self.loadingActivityIndicator.startAnimating()
        UIApplication.shared.beginIgnoringInteractionEvents()
        loading = true
        self.skipBoardError = 0
    }
}
