//
//  OptionViewController.swift
//  Inventory_ATx88
//
//  Created by 류은주 on 2017. 12. 29..
//  Copyright © 2017년 류은주. All rights reserved.
//
let TABLE_VIEW_BUTTON_MODE = 0
let TABLE_VIEW_BUTTON_NOTI = 1
let TABLE_VIEW_ALERT_NOTI = 2


let SUB_VIEW_ALGORITHM = 0
let SUB_VIEW_INVENTORYSET = 1

let DEVICE_MODEL_OTHER = 0
let DEVICE_MODEL_ATD100 = 1
let DEVICE_MODEL_ATS100 = 2
let DEVICE_MODEL_ATS200 = 3

let NOTI_COUNT = 3

import UIKit


class OptionViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate, UITableViewDataSource,  UITableViewDelegate, EADeviceInitializeDelegate, EAReaderDelegate {
    
    @IBOutlet weak var connectBarItem: UIBarButtonItem!
    

    @IBOutlet weak var optionTableView: UITableView!
    @IBOutlet weak var deviceTimeSetView: UIView!
    @IBOutlet weak var datePickerView: UIDatePicker!
    @IBOutlet weak var timePickerView: UIDatePicker!
    @IBOutlet weak var blockView: UIView!

    
    @IBOutlet weak var tableViewTopView: UIView!
    @IBOutlet weak var notiTableView: UITableView!
    
    
    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 devicetype: Int = 0

    
    var rfidmenuItems: NSArray?
    var devicemenuItems: NSArray?
    var buttonNotiData: NSArray?
    var buttonModeData: NSArray = ["NO", "Short", "Long"]
    var buttonModeParamData: NSArray?
    var buttonNotiParamData: NSArray?
    var alertNotiParamData: NSArray?
    var btnmodename = ""
    var btnnotiname = ""
    var alertnotiname = ""
    
    var devicedate: NSDate?
    var devicetime: NSDate?
    var dateset = ""
    var timeset = ""
    
    var btnmodevalue = 0
 
    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(self.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{
        if appDelegate.connectflag == true {
            optionViewInit()
            connectBarItem.title = "Cancel"
            appDelegate.connectflag = true
            
        } else {
            connectBarItem.title = "Search"
            appDelegate.connectflag = false
        }
//        DispatchQueue.main.async(execute: {() -> Void in
            self.optionTableView.reloadData()
//        })
    }
    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.
    }
    */
    // MARK: - Table view data source
    
    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 {
                        self.optionTableView.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.optionTableView.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)
        }
        print("Disconnect Success")
        //        viewinitial()
        //        viewmode(mode: 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 didCompleteInitialize(_ error: Error!) {
        appDelegate.mReader = EAReader(device: mDevice, delegate: readerDelegate)
        print("didCompleteInitialize finish")
        appDelegate.mReader?.setDelegate(self)
  
            if(self.wrongdeviceflag == 0){
                self.appDelegate.connectflag = true
                
            }else {
                self.appDelegate.connectflag = false
                self.wrongdeviceflag = 0;
            }
            self.peripheralArray.removeAllObjects()
        DispatchQueue.main.async {
            self.viewWillAppear(true)
            self.HUD.hide(true)
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if(tableView == optionTableView){
            if (appDelegate.connectflag == true) {
                return devicemenuItems!.count
            } else {
                return peripheralArray.count
            }
        } else {
            if(buttonNotiData == nil){
                return NOTI_COUNT
            } else {
                return (buttonNotiData?.count)!
            }
        }
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
        
        // Configure the cell...
        if(tableView == optionTableView){
            let cell : OptionTableViewCell = tableView.dequeueReusableCell(withIdentifier: "OptionCell", for: indexPath) as! OptionTableViewCell
            if(appDelegate.connectflag == true){
                let CellIdentifier: String = devicemenuItems![indexPath.row] as! String
            
                cell.optionTitle.text = CellIdentifier
                if ((appDelegate.devicemodel == DEVICE_MODEL_ATS100) || (appDelegate.devicemodel == DEVICE_MODEL_ATD100) ||
                    (appDelegate.devicemodel == DEVICE_MODEL_ATS200)) {
                    if(indexPath.row == 0){
                        cell.optionValue.text = appDelegate.mReader?.firmwareVersion()
                    }else if (indexPath.row == 1){
                        cell.optionValue.text = appDelegate.mReader?.serialNumber
                    }else if (indexPath.row == 2){
                        cell.optionValue.text = String(format: "%d sec", (appDelegate.mReader?.autoOffTime)!)
                    }else if (indexPath.row == 3){
                        cell.optionValue.text = btnmodename
                    }else if (indexPath.row == 4){
                        cell.optionValue.text = btnnotiname
                    } else if (indexPath.row == 5) {
                        cell.optionValue.text = alertnotiname
                    } else {
                        cell.optionValue.text = nil;
                    }
                } else {
                    if(indexPath.row == 0){
                        cell.optionValue.text = appDelegate.mReader?.firmwareVersion()
                    }else if (indexPath.row == 1){
                        cell.optionValue.text = appDelegate.mReader?.serialNumber
                    }else if (indexPath.row == 2){
                        cell.optionValue.text = "\(dateset) \(timeset)"
                    }else if (indexPath.row == 3){
                        cell.optionValue.text = String(format: "%d sec", (appDelegate.mReader?.displayOffTime)!)
                    }else if (indexPath.row == 4){
                        cell.optionValue.text = String(format: "%d sec", (appDelegate.mReader?.autoOffTime)!)
                    }else if (indexPath.row == 5){
                        cell.optionValue.text = btnmodename
                    }else if (indexPath.row == 6){
                        cell.optionValue.text = btnnotiname
                    } else if (indexPath.row == 7) {
                        cell.optionValue.text = alertnotiname
                    } else {
                        cell.optionValue.text = nil;
                    }
                }
            
            } else {
                cell.optionTitle.text = (peripheralArray[indexPath.item] as AnyObject).name
                cell.optionValue.text = ""
            }
            return cell
        } else if tableView == notiTableView {
            let cell = tableView.dequeueReusableCell(withIdentifier: "alertCell", for: indexPath) as UITableViewCell
            var paramValue: EADataValue?
            
            if notiTableView.tag == TABLE_VIEW_BUTTON_MODE {
                paramValue = buttonModeParamData?[indexPath.row] as? EADataValue
            } else if notiTableView.tag == TABLE_VIEW_BUTTON_NOTI {
                paramValue = buttonNotiParamData?[indexPath.row] as? EADataValue
            } else {
                paramValue = alertNotiParamData?[indexPath.row] as? EADataValue
            }
    
            cell.textLabel?.text = paramValue?.dataName! as String?
            if paramValue?.dataValue != 0 {
                cell.accessoryType = .checkmark
            }
            else {
                cell.accessoryType = .none
            }
            return cell
        } else {
            let cell : OptionTableViewCell = tableView.dequeueReusableCell(withIdentifier: "OptionCell", for: indexPath) as! OptionTableViewCell
            return cell
        }
       
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if(tableView == optionTableView){
            if(appDelegate.connectflag != true){
                isDeviceOn = false
                if(connectprocess == true) {
                    return
                } else {
                    connectprocess = true
                    appDelegate.mCentralManager?.stopScan()
                    connectBarItem.title = "Search"
                    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)
                    })
                }
            } else {
            if ((appDelegate.devicemodel == DEVICE_MODEL_ATS100) || (appDelegate.devicemodel == DEVICE_MODEL_ATD100)||(appDelegate.devicemodel == DEVICE_MODEL_ATS200)) {
                 if(indexPath.row == 2){
                    self.autoOffTimeSetting()
                } else if(indexPath.row == 3){
                    notiTableView.tag = TABLE_VIEW_BUTTON_MODE
                    initbuttonMode((appDelegate.mReader?.extendBtnmode)!)
                    notiTableView.reloadData()
                    tableViewTopView.isHidden = false
                    notiTableView.isHidden = false
                } else if(indexPath.row == 4){
                    notiTableView.tag = TABLE_VIEW_BUTTON_NOTI
                    initButtonNoti((appDelegate.mReader?.extendNotMode)!)
                    notiTableView.reloadData()
                    tableViewTopView.isHidden = false
                    notiTableView.isHidden = false
                } else if(indexPath.row == 5) {
                    notiTableView.tag = TABLE_VIEW_ALERT_NOTI
                    initalertNoti((appDelegate.mReader?.extendAlertNoty)!)
                    notiTableView.reloadData()
                    tableViewTopView.isHidden = false
                    notiTableView.isHidden = false
                }
            } else {
                if(indexPath.row == 2){
                    getdevicetime()
                    datePickerView.setDate(devicedate! as Date, animated: true)
                    timePickerView.setDate(devicetime! as Date, animated: true)
                    blockView.isHidden = false
                    deviceTimeSetView.isHidden = false
                } else if(indexPath.row == 3){
                    self.displayOffTimeSetting()
                }else if(indexPath.row == 4){
                    self.autoOffTimeSetting()
                } else if(indexPath.row == 5){
                    notiTableView.tag = TABLE_VIEW_BUTTON_MODE
                    initbuttonMode((appDelegate.mReader?.extendBtnmode)!)
                    notiTableView.reloadData()
                    tableViewTopView.isHidden = false
                    notiTableView.isHidden = false
                } else if(indexPath.row == 6){
                    notiTableView.tag = TABLE_VIEW_BUTTON_NOTI
                    initButtonNoti((appDelegate.mReader?.extendNotMode)!)
                    notiTableView.reloadData()
                    tableViewTopView.isHidden = false
                    notiTableView.isHidden = false
                } else if(indexPath.row == 7) {
                    notiTableView.tag = TABLE_VIEW_ALERT_NOTI
                    initalertNoti((appDelegate.mReader?.extendAlertNoty)!)
                    notiTableView.reloadData()
                    tableViewTopView.isHidden = false
                    notiTableView.isHidden = false
                }
            }
            }
        } else{
            let cell: UITableViewCell? = tableView.cellForRow(at: indexPath)
            if notiTableView.tag == TABLE_VIEW_BUTTON_MODE {
                if cell?.accessoryType == .checkmark {
                  
                }else {
                    cell?.accessoryType = .checkmark
                }
                btnmodevalue = indexPath.row
                var arrParam = [AnyHashable]()
                for i in 0..<buttonModeData.count {
                    let paramValue = EADataValue()
                    paramValue.dataName = buttonModeData[i] as! NSString
                    if i == indexPath.row {
                        paramValue.dataValue = 1
                    }
                    else {
                        paramValue.dataValue = 0
                    }
                    arrParam.append(paramValue)
                }
                buttonModeParamData = arrParam as NSArray
            } else {
                var checkmark = false
                if cell?.accessoryType == .checkmark {
                    cell?.accessoryType = .none
                    checkmark = false
                }
                else {
                    if (((appDelegate.devicemodel == DEVICE_MODEL_ATS100 || appDelegate.devicemodel == DEVICE_MODEL_ATS200) && (indexPath.row == 2)) || ((appDelegate.devicemodel == DEVICE_MODEL_ATD100 ) && (indexPath.row == 1))) {
                    
                    } else {
                        cell?.accessoryType = .checkmark
                        checkmark = true
                    }
                }
                var arrParam = [AnyHashable]()
                for i in 0..<NOTI_COUNT{
                    let paramValue = EADataValue()
                    var btnvalue: EADataValue?
                    paramValue.dataName = buttonNotiData![i] as! NSString
                    if notiTableView.tag == TABLE_VIEW_BUTTON_NOTI {
                        btnvalue = buttonNotiParamData?[i] as? EADataValue
                    }
                    else {
                        btnvalue = alertNotiParamData?[i] as? EADataValue
                    }
                    if i == indexPath.row {
                        if(checkmark == true){
                            paramValue.dataValue = 1
                        } else {
                            paramValue.dataValue = 0
                        }
                    }
                    else {
                        paramValue.dataValue = (btnvalue?.dataValue)!
                    }
                    arrParam.append(paramValue)
                }
                if notiTableView.tag == TABLE_VIEW_BUTTON_NOTI {
                    buttonNotiParamData = arrParam as NSArray
                }
                else {
                    alertNotiParamData = arrParam as NSArray
                }
                
            }
            notiTableView.reloadData()
        }
        
    }
    
    
    func optionViewInit() {
        
        if(appDelegate.mReader == nil){
            return
        }
        
        if (appDelegate.mReader?.barcodedeviceget() == 0) || (appDelegate.mReader?.barcodedeviceget() == 2) {
            devicetype = 0
        }else {
            devicetype = 1
        }
        

        if (appDelegate.devicename?.range(of: "ATS100")) != nil {
            appDelegate.devicemodel = DEVICE_MODEL_ATS100
        } else if (appDelegate.devicename?.range(of: "ATS200")) != nil {
            appDelegate.devicemodel = DEVICE_MODEL_ATS200
        }else if (appDelegate.devicename?.range(of: "ATD100")) != nil {
            appDelegate.devicemodel = DEVICE_MODEL_ATD100
        }else {
            appDelegate.devicemodel = DEVICE_MODEL_OTHER
            getdevicetime()
        }
//        if ( self.appDelegate.devicename?.range(of: "ATS100") != nil) {
        if self.appDelegate.devicemodel == DEVICE_MODEL_ATS100 || self.appDelegate.devicemodel == DEVICE_MODEL_ATS200 {
            self.buttonNotiData = ["Beep", "Vibrate", "Ligth(Not Support)"]
        } else if self.appDelegate.devicemodel == DEVICE_MODEL_ATD100 {
            self.buttonNotiData = ["Beep", "Vibrate(Not Support)", "Ligth"]
        }else {
            self.buttonNotiData = ["Beep", "Vibrate", "Ligth"]
        }
        
        initalertNoti((appDelegate.mReader?.extendAlertNoty)!)
        initbuttonMode((appDelegate.mReader?.extendBtnmode)!)
        initButtonNoti((appDelegate.mReader?.extendNotMode)!)
        
        
//        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            // Do something...
            
            if ((appDelegate.devicemodel == DEVICE_MODEL_ATS100) || (appDelegate.devicemodel == DEVICE_MODEL_ATD100) || (appDelegate.devicemodel == DEVICE_MODEL_ATS200)) {
                self.devicemenuItems = ["Firmware Version", "Serial No.", "Auto off Time", "Button Mode", "Button Notify", "Alert Notify"]
            } else {
                self.devicemenuItems = ["Firmware Version", "Serial No.", "Device Time", "Display off Time", "Auto off Time", "Button Mode", "Button Notify", "Alert Notify"]
            }
//        })

    }
    func getdevicetime() {
        let systemtime: String = appDelegate.mReader!.deviceTime
        let year: String = (systemtime as NSString).substring(with: NSRange(location: 4, length: 4))
        let month: String = (systemtime as NSString).substring(with: NSRange(location: 8, length: 2))
        let day: String = (systemtime as NSString).substring(with: NSRange(location: 10, length: 2))
        let hour: String = (systemtime as NSString).substring(with: NSRange(location: 12, length: 2))
        let min: String = (systemtime as NSString).substring(with: NSRange(location: 14, length: 2))
        let dateFormatter = DateFormatter()
        // Time format for the string value
        dateFormatter.dateFormat = "yyyy.MM.dd"
        dateset = "\(year).\(month).\(day)"
        devicedate = dateFormatter.date(from: dateset)! as NSDate
        let timeFormatter = DateFormatter()
        // Time format for the string value
        timeFormatter.dateFormat = "HH:mm"
        timeset = "\(hour):\(min)"
        devicetime = timeFormatter.date(from: timeset)! as NSDate
    }
    func initbuttonMode(_ `set`: Int32) {
        var arrParam = [AnyHashable]()
        for i in 0..<NOTI_COUNT {
            let paramValue = EADataValue()
            paramValue.dataName = buttonModeData[i] as! NSString
            if i == `set` {
                paramValue.dataValue = 1
                btnmodename = buttonModeData[i] as! String
            }
            else {
                paramValue.dataValue = 0
            }
            arrParam.append(paramValue)
        }
        buttonModeParamData = arrParam as NSArray
//        notiTableView.reloadData()
    }
    
    func initButtonNoti(_ `set`: Int32) {
        var arrParam = [AnyHashable]()
        var beep = ""
        var vibrate = ""
        var light = ""
        for i in 0..<NOTI_COUNT {
            let paramValue = EADataValue()
            paramValue.dataName = buttonNotiData![i] as! NSString
            if `set` & (1 << i) > 0 {
                paramValue.dataValue = 1
                if i == 0 {
                    beep = "\(buttonNotiData![i])"
                }
                else if i == 1 {
                    vibrate = "\(buttonNotiData![i])"
                }
                else {
                    light = "\(buttonNotiData![i])"
                }
            } else {
                    paramValue.dataValue = 0
                    if i == 0 {
                        beep = ""
                    }
                    else if i == 1 {
                        vibrate = ""
                    }
                    else {
                        light = ""
                    }
            }
            arrParam.append(paramValue)
        }
            buttonNotiParamData = arrParam as NSArray
            btnnotiname = "\(beep) \(vibrate) \(light)"
//            notiTableView.reloadData()
 
    }
                
    func initalertNoti(_ `set`: Int32) {
        var beep = ""
        var vibrate = ""
        var light = ""
        var arrParam = [AnyHashable]()
        for i in 0..<NOTI_COUNT {
            let paramValue = EADataValue()
            paramValue.dataName = buttonNotiData![i] as! NSString
            if `set` & (1 << i) > 0 {
                paramValue.dataValue = 1
                if i == 0 {
                    beep = "\(buttonNotiData![i])"
                }
                else if i == 1 {
                    vibrate = "\(buttonNotiData![i])"
                }
                else {
                    light = "\(buttonNotiData![i])"
                }
            } else {
                    paramValue.dataValue = 0
                    if i == 0 {
                        beep = ""
                    }
                    else if i == 1 {
                        vibrate = ""
                    }
                    else {
                        light = ""
                    }
                
                }
                arrParam.append(paramValue)
            }
            alertNotiParamData = arrParam as NSArray
            alertnotiname = "\(beep) \(vibrate) \(light)"
//            notiTableView.reloadData()
        }


    func displayOffTimeSetting() {
        let alert = UIAlertController(title: "Display Off Time:", message: """
    Please enter Display Off time.
    (more than 20 sec)
    """, preferredStyle: .alert)
        alert.addTextField(configurationHandler: {(_ textField: UITextField) -> Void in
            textField.keyboardType = .numberPad
        })
        let ok = UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
            let textField: UITextField? = alert.textFields?.first
            if((Int((textField?.text)!)! > 0) && (Int((textField?.text)!)! < 20)) {
                let dialog = UIAlertController(title: "Error", message: "Please enter a bigger number than 20 sec", preferredStyle: .alert)
                let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
                dialog.addAction(action)
                self.present(dialog, animated: true, completion: nil)
                return
            }
            self.appDelegate.mReader?.displayOffTime = Int32(Int(textField!.text ?? "") ?? 0)
            self.optionTableView.reloadData()
            alert.dismiss(animated: true) {() -> Void in }
        })
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: {(_ action: UIAlertAction) -> Void in
            alert.dismiss(animated: true) {() -> Void in }
        })
        alert.addAction(cancel)
        alert.addAction(ok)
        
        DispatchQueue.main.async(execute: {() -> Void in
            self.present(alert, animated: true) {() -> Void in }
        })
    }
    func autoOffTimeSetting(){
        let alert = UIAlertController(title: "Auto Off Time:", message:"Please enter Auto Off time.(ex: 30 sec)", preferredStyle: .alert)
        alert.addTextField(configurationHandler: {(_ textField: UITextField) -> Void in textField.keyboardType = .numberPad })
        let ok = UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
            let textField: UITextField? = alert.textFields?.first
            self.appDelegate.mReader?.autoOffTime = Int32(Int(textField!.text ?? "") ?? 0)
            self.optionTableView.reloadData()
            alert.dismiss(animated: true) {() -> Void in}
        })
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: {(_ action: UIAlertAction) -> Void in
            alert.dismiss(animated: true) {() -> Void in }
        })
        alert.addAction(cancel)
        alert.addAction(ok)
        
        DispatchQueue.main.async(execute: {() -> Void in
            self.present(alert, animated: true) {() -> Void in }
        })
    }

    func hideViews() {
        tableViewTopView.isHidden = true
        notiTableView.isHidden = true
        deviceTimeSetView.isHidden = true
        blockView.isHidden = true
    }
    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
        }
    }
    @IBAction func connectBarItemTapped(_ sender: UIBarButtonItem) {

        if appDelegate.connectflag != true  {
//                self.performSegue(withIdentifier: "BTConnect", sender: nil)
            if connectBarItem.title == "Search" {
                peripheralArray.removeAllObjects()
                mQueue = DispatchQueue(label: "com.atid.bluetooth")
                appDelegate.mCentralManager = CBCentralManager(delegate: self, queue: mQueue)
                DispatchQueue.main.async {
                    self.connectBarItem.title = "Stop"
                }
            } else {
                appDelegate.mCentralManager?.stopScan()
                DispatchQueue.main.async {
                    self.connectBarItem.title = "Search"
                }
            }
        } else {
            appDelegate.connectflag = false
            disconnect()
            viewWillAppear(true)
        }
    }


    @IBAction func tableTopViewCancel(_ sender: UIButton) {
        hideViews()
    }
    
    @IBAction func tableTopViewOK(_ sender: UIButton) {
        if(notiTableView.tag == TABLE_VIEW_BUTTON_MODE){
            appDelegate.mReader?.extendBtnmode = Int32(btnmodevalue)
            initbuttonMode((appDelegate.mReader?.extendBtnmode)!)
        } else if (notiTableView.tag == TABLE_VIEW_BUTTON_NOTI) {
            var value: Int = 0
            for i in 0..<NOTI_COUNT {
                let btnvalue: EADataValue? = buttonNotiParamData?[i] as? EADataValue
                if btnvalue?.dataValue != 0 {
                    value += 1 << i
                }
            }
            appDelegate.mReader?.extendNotMode = Int32(value)
            initButtonNoti((appDelegate.mReader?.extendNotMode)!)
        } else {
            var value: Int = 0
            for i in 0..<NOTI_COUNT {
                let btnvalue: EADataValue? = alertNotiParamData?[i] as? EADataValue
                if btnvalue?.dataValue != 0 {
                    value += 1 << i
                }
            }
            appDelegate.mReader?.extendAlertNoty = Int32(value)
            initalertNoti((appDelegate.mReader?.extendAlertNoty)!)
        }
        hideViews()
        optionTableView.reloadData()
    }
    @IBAction func timeSetCancelTapped(_ sender: UIButton) {
        hideViews()
    }
    @IBAction func timeSetOKTapped(_ sender: UIButton) {
        let df = DateFormatter()
        df.dateFormat = "yyyyMMdd"
        //지정한 날짜 형식으로 날짜를 표시한다.
        let datesetstring = df.string(from: datePickerView.date)
        let tf = DateFormatter()
        tf.dateFormat = "HHmm"
        //지정한 날짜 형식으로 날짜를 표시한다.
        let timesetstring = tf.string(from: timePickerView.date)
        let devicetimestring = "\(datesetstring)\(timesetstring)00"
        appDelegate.mReader?.deviceTime = devicetimestring
        getdevicetime()
        hideViews()
        optionTableView.reloadData()
    }
    @objc func bluetoothDisconnected(_ notification: Notification){
        HUD.hide(true)
        HUD.removeFromSuperview()
        appDelegate.connectflag = false
        appDelegate.mReader = nil
        appDelegate.mPeripheral = nil
        hideViews()
        viewWillAppear(true)
        let dialog = UIAlertController(title: "Connect State", message: "BT Disconnected!!!", preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
        dialog.addAction(action)
//        let ok = UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
//            self.viewWillAppear(true)
//        })
//        dialog.addAction(ok)
        self.present(dialog, animated: true, completion: nil)
    
    }
    @objc func wrongdeviceconnected(_ notification: Notification) {
        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) {
        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
        })
    }

}
