//
//  BTConnectViewController.swift
//  
//
//  Created by 류은주 on 2017. 12. 7..
//
let TABLE_VIEW_CONNECT = 0
let TABLE_VIEW_INVENTORY = 1

import UIKit

class BTConnectViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate, UITableViewDataSource,  UITableViewDelegate, EADeviceInitializeDelegate, EAReaderDelegate
{
    
    @IBOutlet weak var BTDeviceTableView: UITableView!
    @IBOutlet weak var searchBtn: UIButton!

    
    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    var mQueue: DispatchQueue?
    var peripheralArray: NSMutableArray = []
    
    var mDevice = EADeviceBluetoothLe()
    weak var readerDelegate: EAReaderDelegate?
    
     var wrongdeviceflag = 0;
    
    fileprivate let data = NSMutableData()
    
    var HUD = MBProgressHUD()
    
    var isDeviceOn = false
    var connectprocess = false
    var connectName = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        
        let center = NotificationCenter.default
        center.addObserver(self, selector: #selector(bluetoothDisconnected), name: NSNotification.Name.init(rawValue: "BluetoothDisconnected"), object: nil)
        let wrongnoti = NotificationCenter.default
        wrongnoti.addObserver(self, selector: #selector(self.wrongdeviceconnected), name: NSNotification.Name.init(rawValue: "wrongdeviceconnected"), object: nil)
        
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
//        if appDelegate.mPeripheral != nil{
//            viewmode(mode: true)
//            isRssiMode = (appDelegate.mReader?.rssiMode)!
//        } else {
//            viewmode(mode: false)
//        }
//        InventoryTableView.reloadData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if appDelegate.mReader?.getAction() != CommandStop {
            appDelegate.mReader?.stop()
        }
         NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "BluetoothDisconnected"), object: nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storybodard-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.
    }
    */
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOff {
            NotificationCenter.default.post(name: NSNotification.Name("BluetoothDisconnected"), object: self)
        }
        
        guard central.state  == .poweredOn else {
            // In a real app, you'd deal with all the states correctly
            return
        }
        // The state must be CBCentralManagerStatePoweredOn...
        // ... so start scanning
        scan()
    }
    
    /** Scan for peripherals - specifically for our service's 128bit CBUUID
     */
    func scan() {
        
        appDelegate.mCentralManager?.scanForPeripherals(withServices: nil, options: [
            CBCentralManagerScanOptionAllowDuplicatesKey : NSNumber(value: true as Bool)
            ]
        )
        
        print("Scanning started")
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if (peripheral.name == connectName) {
            isDeviceOn = true
        }
        if (( peripheral.name?.range(of: "AT188") != nil) || ( peripheral.name?.range(of: "AT388") != nil) || ( peripheral.name?.range(of: "ATS100") != nil)||( peripheral.name?.range(of: "ATS200") != nil) || ( peripheral.name?.range(of: "AT188NP") != nil)) {
            // Ok, it's in range - have we already seen it?
            
            if appDelegate.mPeripheral != peripheral {
                // Save a local copy of the peripheral, so CoreBluetooth doesn't get rid of it
                
                // And connect
                print("Discover to peripheral \(peripheral)")
                
                if peripheralArray.count < 1 {
                    peripheralArray.addObjects(from: [peripheral])
                    DispatchQueue.main.async(execute: {() -> Void in
                        self.BTDeviceTableView.reloadData()
                    })
                } else {
                    var check = 0
                    for i in 0...peripheralArray.count-1{
                        if peripheral.name == (peripheralArray[i] as AnyObject).name{
                            check = 1
                        }
                    }
                    
                    if check == 0 {
                        peripheralArray.addObjects(from: [peripheral])
                        DispatchQueue.main.async(execute: {() -> Void in
                            self.BTDeviceTableView.reloadData()
                        })
                    }
                }
            }
        }
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Peripheral Connected")
        
        data.length = 0
        
        mDevice = EADeviceBluetoothLe(peripheral: peripheral, delegate: self as EADeviceInitializeDelegate)
        // Stop scanning
        appDelegate.mCentralManager?.stopScan()
        
        print("Scanning stopped")
        
        
    }
    
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        DispatchQueue.main.async(execute: {() -> Void in
            NotificationCenter.default.post(name: NSNotification.Name("BluetoothDisconnected"), object: self)

        })
        print("Disconnect Success")
    }
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            print("Error discovering services: \(error!.localizedDescription)")
            return
        }
        
        guard let stringFromData = NSString(data: characteristic.value!, encoding: String.Encoding.utf8.rawValue) else {
            print("Invalid data")
            return
        }
        
        // Have we got everything we need?
        if stringFromData.isEqual(to: "EOM") {
            // We have, so show the data,
            //            textView.text = String(data: data.copy() as! Data, encoding: String.Encoding.utf8)
            
            // Cancel our subscription to the characteristic
            peripheral.setNotifyValue(false, for: characteristic)
            
            // and disconnect from the peripehral
            appDelegate.mCentralManager?.cancelPeripheralConnection(peripheral)
        } else {
            // Otherwise, just add the data on to what we already have
            data.append(characteristic.value!)
            
            // Log it
            print("Received: \(stringFromData)")
        }
    }
    
    /** The peripheral letting us know whether our subscribe/unsubscribe happened or not
     */
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
        print("Error changing notification state: \(String(describing: error?.localizedDescription))")
        
        // Exit if it's not the transfer characteristic
        //        guard characteristic.uuid.isEqual(transferCharacteristicUUID) else {
        //            return
        //        }
        
        // Notification has started
        if (characteristic.isNotifying) {
            print("Notification began on \(characteristic)")
        } else { // Notification has stopped
            print("Notification stopped on (\(characteristic))  Disconnecting")
            appDelegate.mCentralManager?.cancelPeripheralConnection(peripheral)
        }
    }
    func didCompleteInitialize(_ error: Error!) {
        appDelegate.mReader = EAReader(device: mDevice, delegate: readerDelegate)
        print("didCompleteInitialize finish")
        appDelegate.mReader?.setDelegate(self)
        
        DispatchQueue.main.async(execute: {() -> Void in
            if(self.wrongdeviceflag == 0){
                self.searchBtn.setTitle("SEARCH", for: UIControl.State.normal)
                self.appDelegate.connectflag = true
                self.performSegue(withIdentifier: "WriteMemory", sender: nil)
            }else {
                self.searchBtn.setTitle("SEARCH", for: UIControl.State.normal)
//                self.disconnect()
                self.wrongdeviceflag = 0;
            }
            
            self.HUD.hide(true)
            self.peripheralArray.removeAllObjects()
            self.BTDeviceTableView.reloadData()
        })
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

            return peripheralArray.count

    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BTCell", for: indexPath)
        
        cell.textLabel?.text = (peripheralArray[indexPath.item] as AnyObject).name
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if(BTDeviceTableView.tag == TABLE_VIEW_CONNECT){
            isDeviceOn = false
            if(connectprocess == true) {
                return
            } else {
                connectprocess = true
                appDelegate.mCentralManager?.stopScan()
                connectName = (peripheralArray[indexPath.item] as AnyObject).name
                startScanDevice()
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(1 * Double(NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {() -> Void in
                    self.connectDevice(indexPath.row)
                })
            }
        }
    }
    func disconnect() {
        if appDelegate.mReader != nil {
            appDelegate.mReader?.disconnect()
            appDelegate.mReader = nil
        }
        appDelegate.connectflag = false
       
        
        // cc 종료 확인 필요........
        if appDelegate.mPeripheral != nil {
            appDelegate.mCentralManager?.cancelPeripheralConnection(appDelegate.mPeripheral!)
            appDelegate.mPeripheral = nil
        }
    }
    @objc func bluetoothDisconnected(_ notification: Notification){
        HUD.hide(true)
        HUD.removeFromSuperview()
        appDelegate.mReader = nil
        appDelegate.mPeripheral = nil
        appDelegate.connectflag = false
        let dialog = UIAlertController(title: "Connect State", message: "BT Disconnected!!!", preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
        dialog.addAction(action)
        self.present(dialog, animated: true, completion: nil)
        
//        performSegue(withIdentifier: "BTConnect", sender: nil)
    }
//    func bluetoothDisconnected(){
//        appDelegate.mReader = nil
//        appDelegate.mPeripheral = nil
//        let dialog = UIAlertController(title: "Connect State", message: "BT Disconnected!!!", preferredStyle: .alert)
//        let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
//        dialog.addAction(action)
//        self.present(dialog, animated: true, completion: nil)
//    }

    @IBAction func cancelBarItemTapped(_ sender: UIBarButtonItem) {
        if appDelegate.mReader != nil {
            appDelegate.mReader?.disconnect()
            appDelegate.mReader = nil
        }
        
        if appDelegate.mPeripheral != nil {
            appDelegate.mCentralManager?.cancelPeripheralConnection(appDelegate.mPeripheral!)
            appDelegate.mPeripheral = nil
        }
    }
    
    @IBAction func searchBtnTapped(_ sender: UIButton) {
        if searchBtn.currentTitle == "SEARCH" {
            peripheralArray.removeAllObjects()
            mQueue = DispatchQueue(label: "com.atid.bluetooth")
            appDelegate.mCentralManager = CBCentralManager(delegate: self, queue: mQueue)
            DispatchQueue.main.async(execute: {() -> Void in
                self.searchBtn.setTitle("STOP", for: UIControl.State.normal)
                
            })
        } else {
            appDelegate.mCentralManager?.stopScan()
            if peripheralArray.count >= 1{
                for i in 0...peripheralArray.count-1 {
                    print("Array: \(peripheralArray[i])")
                }
            }
            DispatchQueue.main.async(execute: {() -> Void in
                self.searchBtn.setTitle("SEARCH", for: UIControl.State.normal)
            })
        }
    }

    @objc func wrongdeviceconnected(_ notification: Notification) {
//        appDelegate.mReader?.disconnect()

        wrongdeviceflag = 1
    }
    func startScanDevice() {
        // Make Scan Peripheral Option...
        let options = [
            CBCentralManagerScanOptionAllowDuplicatesKey : (0)
        ]
        //        bleready = 1
        // Start Scan Peripheral Device
        appDelegate.mCentralManager?.scanForPeripherals(withServices: nil, options: options)
        //    }
    }
    func connectDevice(_ index: Int) {
        appDelegate.mCentralManager?.stopScan()
        DispatchQueue.main.async(execute: {() -> Void in
            self.searchBtn.setTitle("SEARCH", for: UIControl.State.normal)
        })
        if isDeviceOn != true {
            let Alert = UIAlertController(title: "Device Power Off", message: "Please check the power of device you want to connect", preferredStyle: .alert)
            let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
            Alert.addAction(action)
            self.present(Alert, animated: true, completion: nil)
            
            connectprocess = false
            
//            peripheralArray.removeAllObjects()
//            InventoryTableView.reloadData()
            return
        }
        
        navigationController?.view.addSubview(HUD)
        DispatchQueue.global(qos: .default).async(execute: {
            self.appDelegate.mCentralManager?.connect(self.peripheralArray[index] as! CBPeripheral, options: nil)
            self.appDelegate.mPeripheral = self.peripheralArray[index] as? CBPeripheral
            self.appDelegate.devicename = (self.peripheralArray[index] as AnyObject).name
            
            DispatchQueue.main.async(execute: {() -> Void in
                self.HUD = MBProgressHUD.showAdded(to: self.view, animated: true);
                self.HUD.labelText = "Connecting..."
                self.HUD.show(true)
            })
            self.connectprocess = false
        })
    }
}
