//
//  BTConnectViewController.swift
//  Inventory_ATx88
//
//  Created by 류은주 on 2017. 12. 7..
//  Copyright © 2017년 류은주. All rights reserved.
//

import UIKit

class BTConnectViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate, UITableViewDataSource,  UITableViewDelegate, EADeviceInitializeDelegate, EAReaderDelegate
{

    @IBOutlet weak var intoInventoryView: UIButton!
    @IBOutlet weak var searchstopBtn: UIButton!
    @IBOutlet weak var disconnectBtn: UIButton!
    @IBOutlet weak var btTableView: UITableView!
    
    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    var mQueue: DispatchQueue?
    var peripheralArray: NSMutableArray = []
    
    var mDevice = EADeviceBluetoothLe()
    weak var readerDelegate: EAReaderDelegate?
    
    
    fileprivate let data = NSMutableData()
    
//    var devicename: String?
    var HUD = MBProgressHUD()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if appDelegate.mPeripheral != nil{
//            intoInventoryView.isHidden = false
//            disconnectBtn.isHidden = false
            btnvisiblechange(state: false)
        } else {
//            intoInventoryView.isHidden = true
//            disconnectBtn.isHidden = true
            btnvisiblechange(state: true)
        }
    }

    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.
    }
    */
    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?.range(of: "AT188") != nil) || ( peripheral.name?.range(of: "AT288") != nil) || ( peripheral.name?.range(of: "AT388") != nil) || ( peripheral.name?.range(of: "ATS100") != 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 {
                        self.btTableView.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 {
                            self.btTableView.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 {
            NotificationCenter.default.post(name: NSNotification.Name("BluetoothDisconnected"), object: self)
            self.bluetoothDisconnected()
//            self.connect.setTitle("Disconnecnt", for: UIControlState.disabled)
//            self.connect.isHidden = true
        }
        print("Disconnect Success")
        btnvisiblechange(state: true)
    }
    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 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) {
        appDelegate.mCentralManager?.connect(peripheralArray[indexPath.item] as! CBPeripheral, options: nil)
        appDelegate.mPeripheral = peripheralArray[indexPath.item] as? CBPeripheral
        appDelegate.devicename = (peripheralArray[indexPath.item] as AnyObject).name
        
        DispatchQueue.main.async {
//            self.settingIndicator.isHidden = false
//            self.settingIndicator.startAnimating()
//
//            let HUD = MBProgressHUD(view: navigationController?.view)
            self.HUD = MBProgressHUD.showAdded(to: self.view, animated: true);
            self.HUD.labelText = "Connecting..."
            self.HUD.show(true)
        }
    }
    func didCompleteInitialize(_ error: Error!) {
        appDelegate.mReader = EAReader(device: mDevice, delegate: readerDelegate)
        print("didCompleteInitialize finish")

        DispatchQueue.main.async {
            self.searchstopBtn.setTitle("SEARCH", for: UIControlState.normal)
//            self.intoInventoryView.isHidden = false
//            self.disconnectBtn.isHidden = false
            self.btnvisiblechange(state: false)
//            self.connect.setTitle("Disconnect", for: UIControlState.normal)
//            self.connect.isHidden = false
//            self.settingIndicator.stopAnimating()
//            self.settingIndicator.isHidden = true
            self.HUD.hide(true)
        }
    }
    
    func btnvisiblechange(state: Bool){
        DispatchQueue.main.async {
            self.intoInventoryView.isHidden = state
            self.disconnectBtn.isHidden = state
        }
    }
    
    @IBAction func searchstopBtnTapped(_ sender: UIButton) {
        if searchstopBtn.currentTitle == "SEARCH" {
            peripheralArray.removeAllObjects()
            mQueue = DispatchQueue(label: "com.atid.bluetooth")
            appDelegate.mCentralManager = CBCentralManager(delegate: self, queue: mQueue)
            DispatchQueue.main.async {
                self.searchstopBtn.setTitle("STOP", for: UIControlState.normal)
                
            }
        } else {
            appDelegate.mCentralManager?.stopScan()
            if peripheralArray.count >= 1{
                for i in 0...peripheralArray.count-1 {
                    print("Array: \(peripheralArray[i])")
                }
            }
            DispatchQueue.main.async {
                self.searchstopBtn.setTitle("SEARCH", for: UIControlState.normal)
            }
        }
    }
    
    @IBAction func disconnectBtnTapped(_ sender: UIButton) {
        appDelegate.mReader?.disconnect()
        
        if appDelegate.mPeripheral != nil {
            appDelegate.mCentralManager?.cancelPeripheralConnection(appDelegate.mPeripheral!)
            appDelegate.mPeripheral = nil
        }
    }
    @IBAction func gotoInventoryTapped(_ sender: UIButton) {
    }
    
    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)
    }
}
