//
//  BarcodeViewController.swift
//  Barcode_ATx88
//
//  Created by 류은주 on 2018. 1. 8..
//  Copyright © 2018년 류은주. All rights reserved.
//



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

    
    //    @IBOutlet weak var intoInventoryView: UIButton!
    @IBOutlet weak var searchstopBtn: UIButton!
    @IBOutlet weak var startstopBtn: UIButton!
    @IBOutlet weak var clearBtn: UIButton!
    @IBOutlet weak var barcodeTableView: UITableView!
    @IBOutlet weak var disconnectBarItem: UIBarButtonItem!
    @IBOutlet weak var optionBarItem: UIBarButtonItem!
    
    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    var mQueue: DispatchQueue?
    var peripheralArray: NSMutableArray = []
    
    var barcodeData: NSMutableArray = []
    
    var mDevice = EADeviceBluetoothLe()
    weak var readerDelegate: EAReaderDelegate?
    var tableFlag = false // false: BTconnect true: Barcode
    
    var wrongdeviceflag = 0;
    
    fileprivate let data = NSMutableData()
    
    //    var devicename: String?
    var HUD = MBProgressHUD()
    
    var isDeviceOn = false
    var connectprocess = false
    var connectName = ""

    var newview = true
    
    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 newview == true {
            let wrongnoti = NotificationCenter.default
            wrongnoti.addObserver(self, selector: #selector(self.wrongdeviceconnected), name: NSNotification.Name.init(rawValue: "wrongdeviceconnected"), object: nil)
            let center = NotificationCenter.default
            center.addObserver(self, selector: #selector(bluetoothDisconnected), name: NSNotification.Name.init(rawValue: "BluetoothDisconnected"), object: nil)
        }
        if appDelegate.mPeripheral != nil{
            appDelegate.mReader?.setDelegate(self)
            tableFlag = true
            btnvisiblechange(state: true)
        } else {
            tableFlag = false
            btnvisiblechange(state: false)
        }

    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "BluetoothDisconnected"), object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "wrongdeviceconnected"), object: nil)
    }
    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() {
        peripheralArray = []
        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.barcodeTableView.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.barcodeTableView.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")
        self.peripheralArray.removeAllObjects()
        self.barcodeData.removeAllObjects()
        btnvisiblechange(state: false)
    }
    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 {
        if(tableFlag == false){
            return peripheralArray.count
        } else {
            return barcodeData.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell : BarcodeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "BarcodeCell", for: indexPath) as! BarcodeTableViewCell
        if(tableFlag == false){
            cell.dataLabel?.text = (peripheralArray[indexPath.item] as AnyObject).name
            cell.subDataLabel.text = ""
            cell.barcodeIdLabel.text = ""
        } else {
            let item: EABarcodeItem? = self.barcodeData[indexPath.row] as? EABarcodeItem
            cell.barcodeIdLabel.text = EABarcodeType.getString((item?.barcodeType)!)
            cell.dataLabel?.text = item?.barcode
            cell.subDataLabel.text = item?.codeId
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if(tableFlag == false){
            if appDelegate.mPeripheral != nil {
                return
            }
            isDeviceOn = false
            if(connectprocess == true) {
                return
            } else {
                connectprocess = true
                appDelegate.mCentralManager?.stopScan()
                self.searchstopBtn.setTitle("SEARCH", for: UIControl.State.normal)
                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 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.searchstopBtn.setTitle("SEARCH", for: UIControl.State.normal)
                self.peripheralArray.removeAllObjects()
                self.barcodeData.removeAllObjects()
                self.btnvisiblechange(state: true)
                self.appDelegate.mReader?.isUseKeyAction = true
                self.appDelegate.mReader?.setTagDataType(TAG_DATA_TYPE_HEX)
                self.appDelegate.mReader?.setPropBarcodeMode(1)
                self.appDelegate.mReader?.charsetset(Int32(self.appDelegate.crtcharset))
            }else {
                self.searchstopBtn.setTitle("SEARCH", for: UIControl.State.normal)
                self.wrongdeviceflag = 0;
            }
            self.HUD.hide(true)
        })
    }
    func btnvisiblechange(state: Bool){
        DispatchQueue.main.async(execute: {() -> Void in
            self.tableFlag = state
            self.searchstopBtn.isHidden = state
            self.startstopBtn.isHidden = !state
            self.clearBtn.isHidden = !state
            self.disconnectBarItem.isEnabled = state
            self.optionBarItem.isEnabled = state
            self.barcodeTableView.reloadData()
        })
    }
    func disconnect() {
        if appDelegate.mReader != nil {
            appDelegate.mReader?.disconnect()
            appDelegate.mReader = nil
        }
        
        
        // cc 종료 확인 필요........
        if appDelegate.mPeripheral != nil {
            appDelegate.mCentralManager?.cancelPeripheralConnection(appDelegate.mPeripheral!)
            appDelegate.mPeripheral = nil
        }
    }
    @objc   func changedActionState(_ action: CommandType) {
        if appDelegate.mReader?.getAction() == CommandInventory {
            return
        }
        if appDelegate.mReader?.getAction() != CommandStop {
            self.startstopBtn.setTitle("STOP", for: UIControl.State.normal)
        } else {
            self.startstopBtn.setTitle("START", for: UIControl.State.normal)
        }
    }
   @objc func barcodeScan(_ barcodeType: BarcodeType, codeId: String, barcode: String) {
        print("BarcodeDemo - barcodeScan : [\(barcodeType), \(codeId), \(barcode)]")
        if barcodeType != BarcodeTypeNoRead {
            let item = EABarcodeItem()
            item.barcodeType = barcodeType
            item.codeId = codeId
            item.barcode = barcode
            barcodeData.addObjects(from: [item])
            barcodeTableView.reloadData()
            barcodeTableView.scrollToRow(at: IndexPath(row: barcodeData.count - 1, section: 0), at: .bottom, animated: true)
//            tagCountLabel.text = "\(UInt(barcodeData.count))"
        }
        else {
            // cc barcode
            print("BarcodeDemo - BarcodeTypeNoRead")
        }
        // cc barcode
        appDelegate.mReader?.stopSync()
    }
    
    @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(execute: {() -> Void in
                self.searchstopBtn.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.searchstopBtn.setTitle("SEARCH", for: UIControl.State.normal)
            })
        }
    }
    @IBAction func disconnectBarItemTapped(_ sender: UIBarButtonItem) {
        disconnect()
    }
    
    @IBAction func startstopBtnTapped(_ sender: UIButton) {
        if appDelegate.mReader?.getAction() != CommandStop {
            appDelegate.mReader?.stop()
        }else {
            appDelegate.mReader?.startScan()
        }
    }
    @IBAction func clearBtnTapped(_ sender: UIButton) {
        barcodeData.removeAllObjects()
        barcodeTableView.reloadData()
    }
    @IBAction func optionBarItemTapped(_ sender: UIBarButtonItem) {
 

        self.performSegue(withIdentifier: "OptionView", sender: nil)

        
        
    }
    @objc func bluetoothDisconnected(_ notification: Notification){
        HUD.hide(true)
        HUD.removeFromSuperview()
        appDelegate.mReader = nil
        appDelegate.mPeripheral = nil
        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)

    }
    @objc func wrongdeviceconnected(_ notification: Notification) {
        wrongdeviceflag = 1
//        appDelegate.mReader?.disconnect()
    }
    
    @objc func opmodesetting(_ mode: Int32) {
        if mode != 1 {
            self.appDelegate.mReader?.setPropBarcodeMode(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) {
        self.appDelegate.mCentralManager?.stopScan()
        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
            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
        })
    }

}
class EABarcodeItem: NSObject {
    
    var barcodeType: BarcodeType?
    var codeId = ""
    var barcode = ""
}
