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

import UIKit

class BurnSelfViewController: UIViewController , NSBluetoothManagerDelegate{
    
    @IBOutlet weak var textLabel: UILabel!
    
    //MARK: - View Properties
    var doubledata: [Double] = [Double]()
    var floatdata: [Float] = [Float]()
    var sender = AppDelegate.MainViews.BURNSELFCORR
    var skipBoardError = 0
    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
            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
                //}
                self.removeLoading()
                self.textLabel.text = "Self-correction 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.runBurnSelf()
            }
        }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
                }
                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.burnSelfDelegate = 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 self-correction settings in DVK ?", preferredStyle: UIAlertControllerStyle.alert)
            
            alertController.addAction(UIAlertAction(title: "Proceed", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
                self.runBurnSelf()
            }))
            
            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 runBurnSelf(){
        if(AppDelegate.bluetoothManager != nil && Constants.BlueToothConnected == true){
            if(self.loading == false){
                self.addLoading()
            }
            AppDelegate.bluetoothManager?.send(data: Constants.BURN_SELF_COMMAND , sender: self.sender)
        }
    }
    
    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
    }
}
