//
//  OptionViewController.swift
//  Inventory_EAReader
//
//  Created by 류은주 on 2017. 12. 29..
//  Copyright © 2017년 류은주. All rights reserved.
//
let PICKER_VIEW_POWER_GAIN = 0
let PICKER_VIEW_INVENTORY_SESSION = 1
let PICKER_VIEW_SESSION_FLAG = 2
let PICKER_VIEW_SELECT_FLAG = 3
let PICKER_VIEW_ALGORITHM = 4
let PICKER_VIEW_LINK_PROFILE = 5
let PICKER_VIEW_DEFAULT_PROFILE = 6
let PICKER_VIEW_ELSE = 7

let SUB_VIEW_ALGORITHM = 0
let SUB_VIEW_INVENTORYSET = 1

import UIKit


class OptionViewController: UIViewController, UITableViewDataSource,  UITableViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource, EAReaderDelegate {
    
    @IBOutlet weak var optionTableView: UITableView!
    @IBOutlet weak var optionTopView: UIView!
    @IBOutlet weak var optionPickerView: UIPickerView!
    @IBOutlet weak var algorithmView: UIView!
    @IBOutlet weak var algorithmTextField: UITextField!
    @IBOutlet weak var startQTextField: UITextField!
    @IBOutlet weak var minQTextField: UITextField!
    @IBOutlet weak var maxQTextField: UITextField!
    @IBOutlet weak var inventorySetView: UIView!
    @IBOutlet weak var selectFlagTextField: UITextField!
    @IBOutlet weak var inventorySessionTextField: UITextField!
    @IBOutlet weak var sessionFlagTextField: UITextField!
    @IBOutlet weak var channelTableView: UITableView!
    
    
    
    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    var rfidmenuItems: NSArray?
    var countryarray: NSArray?
    var powergainData: NSArray?
    var algorithmPickerData: NSArray?
    var powergaintext: String = ""
    var algorithmtext: String = ""
    var selectFlagValue: Int = 0
    var inventorySessionValue: Int = 0
    var sessionFlagValue: Int = 0
    var selectFlagText: String = ""
    var inventorySessionText: String = ""
    var sessionFlagText: String = ""
    var algorithmValue: AlgorithmType = AlgorithmType(rawValue: 0)
    var startQValue: Int32 = 0
    var minQValue: Int32 = 0
    var maxQValue: Int32 = 0
    var channelData: NSArray?
    var linkProfileData: NSArray?
    var linkProfileText: String = ""
    var defaultlinkProfileData: NSArray?
    var defaultProfileText: String = ""
    var smallViewFlag: Int = 0
    var tableFlag = 0
    
    var lbtItemData : NSArray?
    
    var HUD = MBProgressHUD()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.HUD = MBProgressHUD.showAdded(to: self.view, animated: true);
        self.HUD.labelText = "Loading..."
        self.HUD.show(true)
        
        if ( appDelegate.devicename!.range(of: "AT388") != nil) {
            rfidmenuItems = ["Global Band", "Power Gain", "Inventory Time", "Idle Time", "Operation Time", "Auto Save", "Report RSSI", "Selection Mask", "Inventory Set", "Inventory Algorithm","Channel Frequencies","Link Profile", "Default Link Profile"]
        } else if ( appDelegate.devicename?.range(of: "ATS100") != nil || appDelegate.devicename?.range(of: "ATS200") != nil) {
            rfidmenuItems = ["Global Band", "Power Gain", "Inventory Time", "Idle Time", "Operation Time","Report RSSI", "Selection Mask", "Inventory Set", "Inventory Algorithm","Channel Frequencies","Link Profile", "Default Link Profile"]
        }else {
            rfidmenuItems = ["Global Band", "Power Gain", "Inventory Time", "Idle Time", "Operation Time", "Auto Save", "Report RSSI", "Selection Mask", "Inventory Set", "Inventory Algorithm","Channel Frequencies"]
        }
        
        countryarray = ["Korea", "Europe", "North America", "China", "Taiwan", "Brazil", "Malaysia", "HongKong", "Japan", "Japan", "India", "Indonesia", "Japan", "Israel", "Australia", "Newzealand", "Philippines", "Singapore", "Thailand", "Uruguay", "Vietnam", "South Africa"]
        
        powergaintext = "\((appDelegate.mReader?.powerGain)! / 10).0 dB"
        
        algorithmPickerData =  ["Fixed Q","Dynamic Q"];
        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            self.initPowerGainPickerData()
            self.initChannelItemData()
            DispatchQueue.main.async(execute: {() -> Void in
                self.linkProfileData =  ["Profile 0","Profile 1","Profile 2","Profile 3"]
                self.linkProfileText = String(format: "Profile %d", (self.appDelegate.mReader?.linkProfile)!)
                self.defaultProfileText = String(format: "Profile %d", (self.appDelegate.mReader?.defaultProfile)!)
                self.HUD.hide(true)
                self.HUD.removeFromSuperview()
            })
        })
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let center = NotificationCenter.default
        center.addObserver(self, selector: #selector(self.bluetoothDisconnected), name: NSNotification.Name.init(rawValue: "BluetoothDisconnected"), object: nil)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        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 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 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 == channelTableView) {
            if lbtItemData == nil {
                return 0
            } else {
                return lbtItemData!.count
            }
        } else {
            return rfidmenuItems!.count
        }
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
        if (tableView == optionTableView) {
            let cell : OptionTableViewCell = tableView.dequeueReusableCell(withIdentifier: "OptionCell", for: indexPath) as! OptionTableViewCell
            // Configure the cell...
            let CellIdentifier: String = rfidmenuItems![indexPath.row] as! String
            
            cell.optionTitle.text = CellIdentifier
            if ( appDelegate.devicename!.range(of: "ATS100") != nil || appDelegate.devicename!.range(of: "ATS200") != nil) {
                if(indexPath.row == 0){
                    cell.optionValue.text = countryarray![(Int((appDelegate.mReader?.region)!.rawValue))] as? String
                }else if (indexPath.row == 1){
                    cell.optionValue.text = String(format: "%d dB", (appDelegate.mReader?.powerGain)!/10)
                }else if (indexPath.row == 2){
                    cell.optionValue.text = String(format: "%d ms", (appDelegate.mReader?.inventoryTime)!)
                }else if (indexPath.row == 3){
                    cell.optionValue.text = String(format: "%d ms", (appDelegate.mReader?.idleTime)!)
                }else if (indexPath.row == 4){
                    cell.optionValue.text = String(format: "%d ms", (appDelegate.mReader?.operationTime)!)
                }else if (indexPath.row == 5) {
                    if (appDelegate.mReader?.rssiMode)!{
                        cell.optionValue.text = "ON"
                    } else {
                        cell.optionValue.text = "OFF"
                    }
                }else if(indexPath.row == 10){
                    cell.optionValue.text = String(format: "Profile %d", (appDelegate.mReader?.linkProfile)!)
                }else if(indexPath.row == 11){
                    cell.optionValue.text = String(format: "Profile %d", (appDelegate.mReader?.defaultProfile)!)
                }else {
                    cell.optionValue.text = nil;
                }
            } else {
                if(indexPath.row == 0){
                    cell.optionValue.text = countryarray![(Int((appDelegate.mReader?.region)!.rawValue))] as? String
                }else if (indexPath.row == 1){
                    cell.optionValue.text = String(format: "%d dB", (appDelegate.mReader?.powerGain)!/10)
                }else if (indexPath.row == 2){
                    cell.optionValue.text = String(format: "%d ms", (appDelegate.mReader?.inventoryTime)!)
                }else if (indexPath.row == 3){
                    cell.optionValue.text = String(format: "%d ms", (appDelegate.mReader?.idleTime)!)
                }else if (indexPath.row == 4){
                    cell.optionValue.text = String(format: "%d ms", (appDelegate.mReader?.operationTime)!)
                }else if (indexPath.row == 5){
                    if (appDelegate.mReader?.autosaveMode)!{
                        cell.optionValue.text = "ON"
                    } else {
                        cell.optionValue.text = "OFF"
                    }
                } else if (indexPath.row == 6) {
                    if (appDelegate.mReader?.rssiMode)!{
                        cell.optionValue.text = "ON"
                    } else {
                        cell.optionValue.text = "OFF"
                    }
                } else if(indexPath.row == 11){
                    cell.optionValue.text = String(format: "Profile %d", (appDelegate.mReader?.linkProfile)!)
                }else if(indexPath.row == 12){
                    cell.optionValue.text = String(format: "Profile %d", (appDelegate.mReader?.defaultProfile)!)
                }else {
                    cell.optionValue.text = nil;
                }
            }
            
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ChannelCell", for: indexPath)
            cell.textLabel?.text = (lbtItemData![indexPath.row] as! ChannelItem).frequency()
            if((lbtItemData![indexPath.row] as! ChannelItem).mIsUsed == true) {
                cell.accessoryType = .checkmark
            } else {
                cell.accessoryType = .none
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (tableView == optionTableView) {
            if ( appDelegate.devicename!.range(of: "ATS100") != nil ||   appDelegate.devicename!.range(of: "ATS200") != nil) {
                if(indexPath.row == 1){
                    self.powergainSetting()
                } else if(indexPath.row == 2){
                    self.inventoryTimeSetting()
                } else if(indexPath.row == 3){
                    self.idleTimeSetting()
                } else if(indexPath.row == 4){
                    self.operationTimeSetting()
                } else if(indexPath.row == 5){
                    if (appDelegate.mReader?.rssiMode)!{
                        appDelegate.mReader?.rssiMode = false
                    } else {
                        appDelegate.mReader?.rssiMode = true
                    }
                } else if(indexPath.row == 6) {
                    self.performSegue(withIdentifier: "SelectionMask", sender: nil)
                } else if(indexPath.row == 7) {
                    initInventorySet()
                    optionPickerView.tag = PICKER_VIEW_ELSE
                    smallViewFlag = SUB_VIEW_INVENTORYSET
                    optionTopView.isHidden = false
                    inventorySetView.isHidden = false
                } else if(indexPath.row == 8){
                    initQvalue()
                    optionPickerView.tag = PICKER_VIEW_ELSE
                    smallViewFlag = SUB_VIEW_ALGORITHM
                    optionTopView.isHidden = false
                    algorithmView.isHidden = false
                }else if(indexPath.row == 9){
                    optionTopView.isHidden = false
                    channelTableView.reloadData()
                    channelTableView.isHidden = false
                    tableFlag = 1
                }else if(indexPath.row == 10){
                    linkprofileSetting()
                }else if(indexPath.row == 11){
                    defaultlinkprofileSetting()
                }
            } else {
                if(indexPath.row == 1){
                    self.powergainSetting()
                } else if(indexPath.row == 2){
                    self.inventoryTimeSetting()
                } else if(indexPath.row == 3){
                    self.idleTimeSetting()
                }else if(indexPath.row == 4){
                    self.operationTimeSetting()
                } else if(indexPath.row == 5){
                    if (appDelegate.mReader?.autosaveMode)!{
                        appDelegate.mReader?.autosaveMode = false
                    } else {
                        appDelegate.mReader?.autosaveMode = true
                    }
                } else if(indexPath.row == 6){
                    if (appDelegate.mReader?.rssiMode)!{
                        appDelegate.mReader?.rssiMode = false
                    } else {
                        appDelegate.mReader?.rssiMode = true
                    }
                } else if(indexPath.row == 7) {
                    self.performSegue(withIdentifier: "SelectionMask", sender: nil)
                } else if(indexPath.row == 8) {
                    initInventorySet()
                    optionPickerView.tag = PICKER_VIEW_ELSE
                    smallViewFlag = SUB_VIEW_INVENTORYSET
                    optionTopView.isHidden = false
                    inventorySetView.isHidden = false
                } else if(indexPath.row == 9){
                    initQvalue()
                    optionPickerView.tag = PICKER_VIEW_ELSE
                    smallViewFlag = SUB_VIEW_ALGORITHM
                    optionTopView.isHidden = false
                    algorithmView.isHidden = false
                }else if(indexPath.row == 10){
                    optionTopView.isHidden = false
                    channelTableView.isHidden = false
                    tableFlag = 1
                }else if(indexPath.row == 11){
                    linkprofileSetting()
                }else if(indexPath.row == 12){
                    defaultlinkprofileSetting()
                }
            }
            DispatchQueue.main.async(execute: {() -> Void in
                tableView.reloadData()
            })
        } else {
            if (appDelegate.mReader?.region == Region_Japan1) || (appDelegate.mReader?.region == Region_Japan2) || (appDelegate.mReader?.region == Region_Japan3) {
                if((lbtItemData![indexPath.row] as! ChannelItem).mIsUsed == true) {
                    (lbtItemData![indexPath.row] as! ChannelItem).mIsUsed = false
                } else {
                    (lbtItemData![indexPath.row] as! ChannelItem).mIsUsed = true
                }
                channelTableView.reloadData()
            }
        }
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if(optionPickerView.tag == PICKER_VIEW_POWER_GAIN){
            return (powergainData?.count)!
        } else if(optionPickerView.tag == PICKER_VIEW_ALGORITHM){
            return (algorithmPickerData?.count)!
        } else if(optionPickerView.tag == PICKER_VIEW_LINK_PROFILE){
            return (linkProfileData?.count)!
        } else if(optionPickerView.tag == PICKER_VIEW_DEFAULT_PROFILE){
            return (linkProfileData?.count)!
        } else if(optionPickerView.tag == PICKER_VIEW_SELECT_FLAG){
            return DATA_SELECT_FLAG.count
        } else if(optionPickerView.tag == PICKER_VIEW_INVENTORY_SESSION){
            return DATA_INVENTORY_SESSION.count
        } else if(optionPickerView.tag == PICKER_VIEW_SESSION_FLAG){
            return DATA_SESSION_FLAG.count
        } else {
            return (powergainData?.count)!
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if(optionPickerView.tag == PICKER_VIEW_POWER_GAIN){
            return powergainData?.object(at: row) as? String
        } else if(optionPickerView.tag == PICKER_VIEW_ALGORITHM){
            return algorithmPickerData?.object(at: row) as? String
        } else if(optionPickerView.tag == PICKER_VIEW_LINK_PROFILE){
            return linkProfileData?.object(at: row) as? String
        } else if(optionPickerView.tag == PICKER_VIEW_DEFAULT_PROFILE){
            return linkProfileData?.object(at: row) as? String
        } else if(optionPickerView.tag == PICKER_VIEW_SELECT_FLAG){
            return DATA_SELECT_FLAG[row]
        } else if(optionPickerView.tag == PICKER_VIEW_INVENTORY_SESSION){
            return DATA_INVENTORY_SESSION[row]
        } else if(optionPickerView.tag == PICKER_VIEW_SESSION_FLAG){
            return DATA_SESSION_FLAG[row]
        } else {
            return powergainData?.object(at: row) as? String
        }
    }
    
    func powergainSetting() {
        optionPickerView.tag = PICKER_VIEW_POWER_GAIN
        self.optionPickerView.reloadAllComponents()
        if !(powergaintext == ""){
            DispatchQueue.main.async(execute: {()->Void in
                self.optionPickerView.selectRow((self.powergainData?.index(of: self.powergaintext))!, inComponent: 0, animated: false)
            })
        }else {
            self.optionPickerView.selectRow(0, inComponent: 0, animated: false)
        }
        DispatchQueue.main.async(execute: {() -> Void in
            self.optionPickerView.isHidden = false
            self.optionTopView.isHidden = false
        })
        
    }
    func inventoryTimeSetting() {
        let alert: UIAlertController
        if (appDelegate.mReader?.region == Region_Euro){
            alert = UIAlertController(title: "Inventory Time:", message: """
    Please enter Inventory time.
    (ex: 30)
    Min = 50 ms Max = 4000 ms
    If you enter less than 50 or more than 4000 it will not set
    """, preferredStyle: .alert)
        } else if (appDelegate.mReader?.region == Region_Japan1) || (appDelegate.mReader?.region == Region_Japan2) || (appDelegate.mReader?.region == Region_Japan3) {
            alert = UIAlertController(title: "Inventory Time:", message: """
    Please enter Inventory time.
    (ex: 30)
    Min = 50 ms Max = 4000 ms
    If you enter less than 50 or more than 4000 it will not set
    """, preferredStyle: .alert)
        } else {
            alert = UIAlertController(title: "Inventory Time:", message: """
    Please enter Inventory time.
    (ex: 30)
    Min = 50 ms Max = 400 ms
    If you don't enter from 50 to 400 or make sum of Inventory Time and Idle Time less than 400. It will not set
    """, preferredStyle: .alert)
        }
//        let alert = UIAlertController(title: "Inventory Time:", message: """
//    Please enter Inventory time.
//    (ex: 30 ms)
//    """, 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?.inventoryTime = 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 idleTimeSetting(){
        let alert = UIAlertController(title: "Idle Time:", message:"Please enter Idle time.(ex: 30 ms)", 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?.idleTime = 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 operationTimeSetting(){
        let alert: UIAlertController
        if (appDelegate.mReader?.region == Region_Euro){
            alert = UIAlertController(title: "Idle Time:", message: """
    Please enter idle time.
    (ex: 30)
    Min = 100 ms Max = 4000 ms
    If you enter less than 100 or more than 4000 it will not set
    """, preferredStyle: .alert)
        } else if (appDelegate.mReader?.region == Region_Japan1) || (appDelegate.mReader?.region == Region_Japan2) || (appDelegate.mReader?.region == Region_Japan3) {
            alert = UIAlertController(title: "Idle Time:", message: """
    Please enter idle time.
    (ex: 30)
    Min = 50 ms Max = 4000 ms
    If you enter less than 50 or more than 400 it will not set
    """, preferredStyle: .alert)
        } else {
            alert = UIAlertController(title: "Idle Time:", message: """
    Please enter idle time.
    (ex: 30)
    Max = 400 ms
    If you enter more than 400 or make sum of Inventory Time and Idle Time more than 400 It will not set
    """, preferredStyle: .alert)
        }
//        let alert = UIAlertController(title: "Operation Time:", message:"Please enter Operation time.(ex: 30 ms)", 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?.operationTime = 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() {
        optionPickerView.isHidden = true
        optionTopView.isHidden = true
        algorithmView.isHidden = true
        inventorySetView.isHidden = true
        channelTableView.isHidden = true
        tableFlag = 0
    }
    func initPowerGainPickerData() {
        if(powergainData == nil) {
            var tmpArray = [AnyHashable]()
            let min = appDelegate.mReader?.powerGainScope().min
            let max = appDelegate.mReader?.powerGainScope().max
            
            var i: Int32
            i = min!
            while i<=max! {
                tmpArray.append("\(i/10).0 dB")
                i += 10
            }
            powergainData = tmpArray as NSArray
        }
    }
    func initQvalue(){
        self.algorithmValue = (appDelegate.mReader?.getAlgorithm())!
        algorithmtext = (self.algorithmPickerData?[Int(algorithmValue.rawValue)] as? String)!
        self.startQValue = (self.appDelegate.mReader?.startQ)!
        self.minQValue = (self.appDelegate.mReader?.minQ)!
        self.maxQValue = (self.appDelegate.mReader?.maxQ)!
        DispatchQueue.main.async(execute: {() -> Void in
            self.algorithmTextField.text = self.algorithmtext
            self.startQTextField.text = "\(self.startQValue)"
            self.maxQTextField.text = "\(self.maxQValue)"
            self.minQTextField.text = "\(self.minQValue)"
        })
    }
    func initInventorySet(){
        selectFlagValue = Int(Float(((appDelegate.mReader?.useSelectionMask)?.rawValue)!))
        inventorySessionValue = Int(Float(((appDelegate.mReader?.inventorySession)?.rawValue)!))
        sessionFlagValue = Int(Float(((appDelegate.mReader?.sessionFlag)?.rawValue)!))
        
        if(selectFlagValue == 0){
            selectFlagText = DATA_SELECT_FLAG[(selectFlagValue)]
        } else {
            selectFlagText = DATA_SELECT_FLAG[(selectFlagValue-1)]
        }
        inventorySessionText = DATA_INVENTORY_SESSION[inventorySessionValue]
        sessionFlagText = DATA_SESSION_FLAG[sessionFlagValue]
        
        selectFlagTextField.text = selectFlagText
        inventorySessionTextField.text = inventorySessionText
        sessionFlagTextField.text = sessionFlagText
        
    }
    
    func initChannelItemData() {
        var lbtItemvary = [AnyHashable]()
        if lbtItemData == nil {
            let lbtItems = appDelegate.mReader?.getChannel()! as NSArray?
            
            //        print("initChannelItemData \(lbtItems![0])")
            
            for i in 0..<lbtItems!.count {
                let lbtItem = lbtItems![i] as! ChannelItem
                let slotfrequency = appDelegate.mReader?.getChannelFrequency(lbtItem.mSlot)
                lbtItem.setFrequency(slotfrequency!)
                lbtItemvary.append(lbtItem)
            }
            lbtItemData = lbtItemvary as NSArray
            for i in 0..<lbtItemData!.count {
                print("lbtItemData[\(i)].frequency: \((lbtItemData![i] as! ChannelItem).frequency())")
                print("lbtItemData[\(i)].mIsUsed: \((lbtItemData![i] as! ChannelItem).mIsUsed)")
            }
        }
        channelTableView.reloadData()
    }
    func linkprofileSetting() {
        optionPickerView.tag = PICKER_VIEW_LINK_PROFILE
        self.optionPickerView.reloadAllComponents()
        if !(linkProfileText == ""){
            DispatchQueue.main.async(execute: {()->Void in
                self.optionPickerView.selectRow((self.linkProfileData?.index(of: self.linkProfileText))!, inComponent: 0, animated: false)
            })
        }else {
            self.optionPickerView.selectRow(0, inComponent: 0, animated: false)
        }
        DispatchQueue.main.async(execute: {() -> Void in
            self.optionPickerView.isHidden = false
            self.optionTopView.isHidden = false
        })
        
    }
    func defaultlinkprofileSetting() {
        optionPickerView.tag = PICKER_VIEW_DEFAULT_PROFILE
        self.optionPickerView.reloadAllComponents()
        if !(defaultProfileText == ""){
            DispatchQueue.main.async(execute: {()->Void in
                self.optionPickerView.selectRow((self.linkProfileData?.index(of: self.defaultProfileText))!, inComponent: 0, animated: false)
            })
        }else {
            self.optionPickerView.selectRow(0, inComponent: 0, animated: false)
        }
        DispatchQueue.main.async(execute: {() -> Void in
            self.optionPickerView.isHidden = false
            self.optionTopView.isHidden = false
        })
        
    }
    
    @IBAction func topviewOK(_ sender: UIButton) {
        if(tableFlag == 0){
            var idx = (Int32(optionPickerView.selectedRow(inComponent: 0)))
            if(optionPickerView.tag == PICKER_VIEW_POWER_GAIN) {
                idx += (appDelegate.mReader?.powerGainScope().min)! / 10
                optionTableView.reloadData()
                appDelegate.mReader?.powerGain = Int32(Int(idx) * 10)
                powergaintext = "\(idx).0 dB"
                optionPickerView.tag = PICKER_VIEW_ELSE
                hideViews()
            } else if(optionPickerView.tag == PICKER_VIEW_SELECT_FLAG){
                selectFlagText = DATA_SELECT_FLAG[Int(idx)]
                selectFlagTextField.text = selectFlagText
                selectFlagValue = Int(idx+1)
                optionPickerView.isHidden = true
                inventorySetView.isHidden = false
                optionPickerView.tag = PICKER_VIEW_ELSE
            } else if(optionPickerView.tag == PICKER_VIEW_INVENTORY_SESSION){
                inventorySessionText = DATA_INVENTORY_SESSION[Int(idx)]
                inventorySessionTextField.text = inventorySessionText
                inventorySessionValue = Int(idx)
                optionPickerView.isHidden = true
                inventorySetView.isHidden = false
                optionPickerView.tag = PICKER_VIEW_ELSE
            } else if(optionPickerView.tag == PICKER_VIEW_SESSION_FLAG){
                sessionFlagText = DATA_SESSION_FLAG[Int(idx)]
                sessionFlagTextField.text = sessionFlagText
                sessionFlagValue = Int(idx)
                optionPickerView.isHidden = true
                inventorySetView.isHidden = false
                optionPickerView.tag = PICKER_VIEW_ELSE
            } else if(optionPickerView.tag == PICKER_VIEW_ALGORITHM){
                algorithmTextField.text = algorithmPickerData?[Int(idx)] as? String
                algorithmValue = AlgorithmType(rawValue: AlgorithmType.RawValue(idx))
                optionPickerView.isHidden = true
                algorithmView.isHidden = false
                optionPickerView.tag = PICKER_VIEW_ELSE
            } else if(optionPickerView.tag == PICKER_VIEW_LINK_PROFILE){
                appDelegate.mReader?.linkProfile = idx
                linkProfileText = String(format: "Profile %d", idx)
                optionPickerView.isHidden = true
                optionPickerView.tag = PICKER_VIEW_ELSE
                optionTableView.reloadData()
                hideViews()
            } else if(optionPickerView.tag == PICKER_VIEW_DEFAULT_PROFILE){
                appDelegate.mReader?.defaultProfile = idx
                defaultProfileText = String(format: "Profile %d", idx)
                optionPickerView.isHidden = true
                optionPickerView.tag = PICKER_VIEW_ELSE
                optionTableView.reloadData()
                hideViews()
            } else if(optionPickerView.tag == PICKER_VIEW_ELSE){
                if(smallViewFlag == SUB_VIEW_ALGORITHM){
                    appDelegate.mReader?.algorithm = algorithmValue
                    appDelegate.mReader?.startQ = Int32(startQValue)
                    appDelegate.mReader?.minQ = Int32(minQValue)
                    appDelegate.mReader?.maxQ = Int32(maxQValue)
                } else if(smallViewFlag == SUB_VIEW_INVENTORYSET){
                    appDelegate.mReader?.useSelectionMask = SelectFlag(rawValue: SelectFlag.RawValue(selectFlagValue))
                    appDelegate.mReader?.inventorySession = SessionType(rawValue: SessionType.RawValue(inventorySessionValue))
                    appDelegate.mReader?.sessionFlag = SessionFlag(rawValue: SessionFlag.RawValue(sessionFlagValue))
                }
                hideViews()
            }
        } else {
            if (appDelegate.mReader?.region == Region_Japan1) || (appDelegate.mReader?.region == Region_Japan2) || (appDelegate.mReader?.region == Region_Japan3) {
                appDelegate.mReader?.setChannel(lbtItemData as! [Any])
            }
            hideViews()
        }
    }
    @IBAction func topviewCancel(_ sender: UIButton) {
        if(optionPickerView.tag == PICKER_VIEW_ALGORITHM){
            optionPickerView.isHidden = true
            algorithmView.isHidden = false
            optionPickerView.tag = PICKER_VIEW_ELSE
        } else if((optionPickerView.tag == PICKER_VIEW_SELECT_FLAG) || (optionPickerView.tag == PICKER_VIEW_INVENTORY_SESSION) || (optionPickerView.tag == PICKER_VIEW_SESSION_FLAG)){
            optionPickerView.isHidden = true
            inventorySetView.isHidden = false
            optionPickerView.tag = PICKER_VIEW_ELSE
        } else {
            hideViews()
        }
    }
    @IBAction func selectFlagBtn(_ sender: UIButton) {
        optionPickerView.tag = PICKER_VIEW_SELECT_FLAG
        self.optionPickerView.reloadAllComponents()
        if !(selectFlagText == ""){
            DispatchQueue.main.async(execute: {()->Void in
                self.optionPickerView.selectRow((DATA_SELECT_FLAG.index(of: self.selectFlagText))!, inComponent: 0, animated: false)
            })
        }else {
            self.optionPickerView.selectRow(0, inComponent: 0, animated: false)
        }
        DispatchQueue.main.async(execute: {() -> Void in
            self.inventorySetView.isHidden = true
            self.optionPickerView.isHidden = false
        })
    }
    @IBAction func inventorySessionBtn(_ sender: UIButton) {
        optionPickerView.tag = PICKER_VIEW_INVENTORY_SESSION
        self.optionPickerView.reloadAllComponents()
        if !(inventorySessionText == ""){
            DispatchQueue.main.async(execute: {()->Void in
                self.optionPickerView.selectRow((DATA_INVENTORY_SESSION.index(of: self.inventorySessionText))!, inComponent: 0, animated: false)
            })
        }else {
            self.optionPickerView.selectRow(0, inComponent: 0, animated: false)
        }
        DispatchQueue.main.async(execute: {() -> Void in
            self.inventorySetView.isHidden = true
            self.optionPickerView.isHidden = false
        })
    }
    @IBAction func sessionFlagBtn(_ sender: UIButton) {
        optionPickerView.tag = PICKER_VIEW_SESSION_FLAG
        self.optionPickerView.reloadAllComponents()
        if !(sessionFlagText == ""){
            DispatchQueue.main.async(execute: {()->Void in
                self.optionPickerView.selectRow((DATA_SESSION_FLAG.index(of: self.sessionFlagText))!, inComponent: 0, animated: false)
            })
        }else {
            self.optionPickerView.selectRow(0, inComponent: 0, animated: false)
        }
        DispatchQueue.main.async(execute: {() -> Void in
            self.inventorySetView.isHidden = true
            self.optionPickerView.isHidden = false
        })
    }
    @IBAction func algorithmBtn(_ sender: UIButton) {
        optionPickerView.tag = PICKER_VIEW_ALGORITHM
        self.optionPickerView.reloadAllComponents()
        if !(algorithmtext == ""){
            DispatchQueue.main.async(execute: {()->Void in
                self.optionPickerView.selectRow((self.algorithmPickerData?.index(of: self.algorithmtext))!, inComponent: 0, animated: false)
            })
        }else {
            self.optionPickerView.selectRow(0, inComponent: 0, animated: false)
        }
        DispatchQueue.main.async(execute: {() -> Void in
            self.algorithmView.isHidden = true
            self.optionPickerView.isHidden = false
        })
    }
    
    @IBAction func startQBtn(_ sender: UIButton) {
        
        let alert = UIAlertController(title: "StartQ:", message:"Please enter StartQ value.", 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.startQValue = Int32(Int(textField!.text ?? "") ?? 0)
            self.startQTextField.text = "\(self.startQValue)"
            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 }
        })
        
    }
    @IBAction func minQBtn(_ sender: UIButton) {
        let alert = UIAlertController(title: "MinQ:", message:"Please enter MinQ value.", 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.minQValue = Int32(Int(textField!.text ?? "") ?? 0)
            self.minQTextField.text = "\(self.minQValue)"
            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 }
        })
    }
    @IBAction func maxQBtn(_ sender: UIButton) {
        let alert = UIAlertController(title: "MaxQ:", message:"Please enter MaxQ value.", 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.maxQValue = Int32(Int(textField!.text ?? "") ?? 0)
            self.maxQTextField.text = "\(self.maxQValue)"
            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 }
        })
    }
    @objc func bluetoothDisconnected(_ notification: Notification){
        DispatchQueue.main.async(execute: {() -> Void in
            self.HUD.hide(true)
            self.HUD.removeFromSuperview()
            self.appDelegate.connectflag = false
            self.performSegue(withIdentifier: "WriteMemory", sender: nil)
        })
    }
    
}

private var UIB_FREQUENCY_KEY = 0
extension ChannelItem {
    //    private var UIB_FREQUENCY_KEY = 0
    
    func setFrequency(_ frequency: String) {
        objc_setAssociatedObject(self, &UIB_FREQUENCY_KEY, frequency, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    
    func frequency() -> String {
        return (objc_getAssociatedObject(self, &UIB_FREQUENCY_KEY) as? String) ?? ""
    }
}


