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


let SUB_TABLE_VIEW_SYMBOL = 0
let SUB_TABLE_VIEW_GENERAL = 1
let SUB_TABLE_VIEW_CHARSET = 2

let PICKER_VIEW_NONE = 0
let PICKER_VIEW_REDUNDANCY_LEVEL = 1
let PICKER_VIEW_SECURITY_LEVEL = 2
let PICKER_VIEW_1D_INVERSE = 3
let PICKER_VIEW_VIDEO_REVERSE = 4

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 optionSubTableView: UITableView!
    @IBOutlet weak var generalOptionTableView: UITableView!
    @IBOutlet weak var charsetTopView: UIView!
    @IBOutlet weak var generalOptionTopView: UIView!
    @IBOutlet weak var generalOptionPickerView: UIPickerView!
    
    
    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    
  ///////////////////////////// ****************************  /////////////////////////////
    var barcodemenuItems: NSArray?
    var barcodeParamData: NSArray?
    var tmpArray = [String]()
    var generalOptionParamData: NSArray?
    var charsetData: NSArray?
    var redundancyPickerData: NSArray?
    var securityPickerData: NSArray?
    var oneDinversePickerData: NSArray?
    var videoReversePickerData: NSArray?
//    var crtcharset = 0
    
    var devicetype: Int?
    var selectedcell = 0
    var isShowingAlert = false
    
    var topviewflag = 0
    var pickerviewflag = false
    
    var HUD = MBProgressHUD()
    
    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)
 ///////////////////////////// ****************************  /////////////////////////////
        self.HUD = MBProgressHUD(view: self.navigationController?.view)
        self.HUD.labelText = "Loading..."
        self.HUD.show(true)
        self.navigationController?.view.addSubview(self.HUD)
        barcodemenuItems = ["Symbologies State","Enable All Symbologies","Disable All Symbologies","Default All Symbologies","General Option","Char Set"]
        charsetData = ["Western (ASCII)", "Western (Mac OS Roman)", "Japanese (Mac OS)", "Traditional Chinese (Mac OS)", "Korean (Mac OS)", "Greek (Mac OS)", "Cyrillic (Mac OS)", "Thai (Mac OS)", "Simplified Chinese (Mac OS)", "Central European (Mac OS)", "Symbol (Mac OS)", "Dingbats (Mac OS)", "Turkish (Mac OS)", "Croatian (Mac OS)", "Icelandic (Mac OS)", "Romanian (Mac OS)", "Unicode™ (UTF-16)", "Unicode™ (UTF-8)", "Western (ISO Latin 1)", "Central European (ISO Latin 2)", "Western (ISO Latin 3)", "Central European (ISO Latin 4)", "Cyrillic (ISO 8859-5)", "Arabic (ISO 8859-6)", "Greek (ISO 8859-7)", "Hebrew (ISO 8859-8)", "Turkish (ISO Latin 5)", "Nordic (ISO Latin 6)", "Thai (ISO 8859-11)", "Baltic Rim (ISO Latin 7)", "Celtic (ISO Latin 8)", "Western (ISO Latin 9)", "Latin-US (DOS)", "Greek (DOS)", "Baltic Rim (DOS)", "Western (DOS Latin 1)", "Central European (DOS Latin 2)", "Turkish (DOS)", "Icelandic (DOS)", "Arabic (DOS)", "Cyrillic (DOS)", "Thai (Windows, DOS)", "Japanese (Windows, DOS)", "Simplified Chinese (Windows, DOS)", "Korean (Windows, DOS)", "Traditional Chinese (Windows, DOS)", "Western (Windows Latin 1)", "Central European (Windows Latin 2)", "Cyrillic (Windows)", "Greek (Windows)", "Turkish (Windows Latin 5)", "Hebrew (Windows)", "Arabic (Windows)", "Baltic Rim (Windows)", "Vietnamese (Windows)", "Chinese (GB 18030)", "Japanese (ISO 2022-JP)", "Korean (ISO 2022-KR)", "Japanese (EUC)", "Simplified Chinese (EUC)", "Korean (EUC)", "Japanese (Shift JIS)", "Cyrillic (KOI8-R)", "Traditional Chinese (Big 5)", "Western (Mac Mail)", "Traditional Chinese (Big 5 HKSCS)", "Western (NextStep)", "Non-lossy ASCII"]
        
        securityPickerData = ["Security Level 0", "Security Level 1", "Security Level 2", "Security Level 3"]
        oneDinversePickerData = ["Regular", "Inverse Only", "Inverse Autodetect"]
        videoReversePickerData = ["Video Reverse Off", "Video Reverse Only", "Video Reverse and Standard Bar Codes"]
        if appDelegate.mReader?.barcodedeviceget() == 0 {
            redundancyPickerData = ["Redundancy Level 1", "Redundancy Level 2", "Redundancy Level 3", "Redundancy Level 4"]
        }
        else {
            redundancyPickerData = ["Disable Bi-directional Redundancy", "Enable Bi-directional Redundancy"]
        }



        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            self.deviceSymbolInit()
        })

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        isShowingAlert = false
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "BluetoothDisconnected"), object: nil)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "SymbolDetail") {
            let indexPath = sender as? IndexPath
            let vc = segue.destination as? SymbolSettingViewController
            vc?.selectedSymbol = (indexPath?.row)!
        } else if (segue.identifier == "symbolZsetting") {
            let indexPath = sender as? IndexPath
            let vc = segue.destination as? SymbolZSettingViewController
            vc?.selectedSymbol = indexPath?.row
        }
        
    }
    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 numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == PICKER_VIEW_REDUNDANCY_LEVEL {
            return redundancyPickerData!.count
        }
        else if pickerView.tag == PICKER_VIEW_SECURITY_LEVEL {
            return securityPickerData!.count
        }
        else if pickerView.tag == PICKER_VIEW_1D_INVERSE {
            return oneDinversePickerData!.count
        }
        else if pickerView.tag == PICKER_VIEW_VIDEO_REVERSE {
            return videoReversePickerData!.count
        }
        
        return 0
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if pickerView.tag == PICKER_VIEW_REDUNDANCY_LEVEL {
            return redundancyPickerData![row] as? String
        }
        else if pickerView.tag == PICKER_VIEW_SECURITY_LEVEL {
            return securityPickerData![row] as? String
        }
        else if pickerView.tag == PICKER_VIEW_1D_INVERSE {
            return oneDinversePickerData![row] as? String
        }
        else if pickerView.tag == PICKER_VIEW_VIDEO_REVERSE {
            return videoReversePickerData![row] as? String
        }

        return "None"
    }
    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) {
            return barcodemenuItems!.count
        } else if (tableView == generalOptionTableView) {
            if(generalOptionParamData == nil){
                return 0
            } else {
                return (generalOptionParamData?.count)!
            }
        } else {
            if(optionSubTableView.tag == SUB_TABLE_VIEW_SYMBOL){
                if(barcodeParamData == nil){
                    return 0
                } else {
                    return (barcodeParamData?.count)!
                }
            }  else {
                return (charsetData?.count)!
            }
        }
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if(tableView == optionTableView) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "OptionCell", for: indexPath)
        
         let CellIdentifier: String = barcodemenuItems![indexPath.row] as! String
        
        cell.textLabel?.text = CellIdentifier
 
            return cell
        } else if tableView == generalOptionTableView {
            let cell = tableView.dequeueReusableCell(withIdentifier: "GeneralOptionCell", for: indexPath) as? GeneralSymbolTableViewCell
            var paramValue: EAParamValue?
            paramValue = generalOptionParamData![indexPath.row] as? EAParamValue
            //             cell.memuname.text = [EAParamName msg:paramValue.paramName];
            if appDelegate.mReader?.barcodedeviceget() == 1 {
                cell?.menuname.text = EAParamName.getName((paramValue?.paramName)!)
                if let aValue = paramValue?.value {
                    cell?.menuvalue.text = videoReversePickerData?[Int(aValue)] as? String
                }
            } else {
                cell?.menuname.text = EAParamName.msg((paramValue?.paramName)!)
                if indexPath.row == 0 {
                    if appDelegate.mReader?.barcodedeviceget() == 2 {
                        cell?.menuvalue.text = redundancyPickerData?[Int(paramValue!.value)] as? String
                    }
                    else {
                        if paramValue!.value > 0 {
                            cell?.menuvalue.text = redundancyPickerData?[Int(paramValue!.value) - 1] as? String
                        }
                    }
                }
                else if indexPath.row == 1 {
                    cell?.menuvalue.text = securityPickerData?[Int(paramValue!.value)] as? String
                }
                else if indexPath.row == 2 {
                    cell?.menuvalue.text = oneDinversePickerData?[Int(paramValue!.value)] as? String
                }
            }
            return cell!
        } else {
            if(optionSubTableView.tag == SUB_TABLE_VIEW_SYMBOL){
                let cell = tableView.dequeueReusableCell(withIdentifier: "OptionSubCell", for: indexPath)
                
                let paramValue: EAParamValue = (barcodeParamData?[indexPath.row] as? EAParamValue)!
                
                if(devicetype == 0){
                    cell.textLabel?.text = EAParamName.msg(paramValue.paramName)
                } else {
                    cell.textLabel?.text = EAParamName.getName(paramValue.paramName)
                }
                
                if(paramValue.value == 1) {
                    cell.accessoryType = .checkmark
                } else {
                    cell.accessoryType = .none
                }
                
                let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.symboldetail))
                recognizer.minimumPressDuration = 1.0
                //seconds
                cell.addGestureRecognizer(recognizer)
                
                return cell
            }  else {
                let cell = tableView.dequeueReusableCell(withIdentifier: "OptionSubCell", for: indexPath)
               
                cell.textLabel?.text = charsetData?[indexPath.row] as? String
                
                if(indexPath.row == appDelegate.crtcharset) {
                    cell.accessoryType = .checkmark
                } else {
                    cell.accessoryType = .none
                }
                return cell
            }
        }        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if(tableView == optionTableView){
            if(indexPath.row == 0){
                optionSubTableView.tag = SUB_TABLE_VIEW_SYMBOL
//                DispatchQueue.main.async(execute: {() -> Void in
                    self.optionSubTableView.reloadData()
//                })
                hideViews()
                optionSubTableView.isHidden = false
                optionTopView.isHidden = false
            } else if(indexPath.row == 1){
                symbolAllSetting(enable: 1)
            } else if(indexPath.row == 2) {
                symbolAllSetting(enable: 0)
            } else if(indexPath.row == 3) {
                symbolDefaultAllSetting()
            } else if(indexPath.row == 4) {
                generalOptionInit()
                generalOptionTableView.reloadData()
                hideViews()
                generalOptionTableView.isHidden = false
                generalOptionTopView.isHidden = false
            } else if(indexPath.row == 5) {
                optionSubTableView.tag = SUB_TABLE_VIEW_CHARSET
//                DispatchQueue.main.async(execute: {() -> Void in
                    self.optionSubTableView.reloadData()
//                })
                hideViews()
                optionSubTableView.isHidden = false
                charsetTopView.isHidden = false
            }
//            DispatchQueue.main.async(execute: {() -> Void in
                tableView.reloadData()
//            })
        } else if tableView == generalOptionTableView {
            var paramValue: EAParamValue?
            paramValue = generalOptionParamData![indexPath.row] as? EAParamValue
            topviewflag = indexPath.row
            pickerviewflag = true
            if appDelegate.mReader?.barcodedeviceget() == 1 {
                if indexPath.row == 0 {
                    generalOptionPickerView.tag = PICKER_VIEW_VIDEO_REVERSE
                    generalOptionPickerView.reloadAllComponents()
                    if let aValue = paramValue?.value {
                        generalOptionPickerView.selectRow(Int(aValue), inComponent: 0, animated: false)
                    }
                    generalOptionTopView.isHidden = true
                    generalOptionPickerView.isHidden = false
                    generalOptionTopView.isHidden = false
//                    shadowview.isHidden = false
                }
            }
            else {
                if indexPath.row == 0 {
                    generalOptionPickerView.tag = PICKER_VIEW_REDUNDANCY_LEVEL
                    generalOptionPickerView.reloadAllComponents()
                    if appDelegate.mReader?.barcodedeviceget() == 2 {
                        if let aValue = paramValue?.value {
                            generalOptionPickerView.selectRow(Int(aValue), inComponent: 0, animated: false)
                        }
                    }
                    else {
                        generalOptionPickerView.selectRow(Int(paramValue!.value) - 1, inComponent: 0, animated: false)
                    }
                    generalOptionTopView.isHidden = true
                    generalOptionPickerView.isHidden = false
                    generalOptionTopView.isHidden = false
//                    shadowview.ishidden = false
                } else if indexPath.row == 1 {
                    generalOptionPickerView.tag = PICKER_VIEW_SECURITY_LEVEL
                    generalOptionPickerView.reloadAllComponents()
                    if let aValue = paramValue?.value {
                        generalOptionPickerView.selectRow(Int(aValue), inComponent: 0, animated: false)
                    }
                    generalOptionTopView.isHidden = true
                    generalOptionPickerView.isHidden = false
                    generalOptionTopView.isHidden = false
//                    shadowview.hidden = false
                } else if indexPath.row == 2 {
                    generalOptionPickerView.tag = PICKER_VIEW_1D_INVERSE
                    generalOptionPickerView.reloadAllComponents()
                    if let aValue = paramValue?.value {
                        generalOptionPickerView.selectRow(Int(aValue), inComponent: 0, animated: false)
                    }
                    generalOptionTopView.isHidden = true
                    generalOptionPickerView.isHidden = false
                    generalOptionTopView.isHidden = false
//                    shadowview.ishidden = false
                }
            }
        } else {
            if(optionSubTableView.tag == SUB_TABLE_VIEW_SYMBOL){
                let cell:UITableViewCell = tableView.cellForRow(at: indexPath)!
                if(cell.accessoryType == .checkmark){
                    cell.accessoryType = .none
                    tmpArray[indexPath.row] = "0"
                } else {
                    cell.accessoryType = .checkmark
                    tmpArray[indexPath.row] = "1"
                }
            } else {
                let cell:UITableViewCell = tableView.cellForRow(at: indexPath)!
                
                cell.accessoryType = .checkmark
                
                appDelegate.crtcharset = indexPath.row
                
                appDelegate.mReader?.charsetset(Int32(appDelegate.crtcharset))
                
//                DispatchQueue.main.async(execute: {() -> Void in
                    self.optionSubTableView.reloadData()
//                })
            }
        }
    }
    
    func deviceSymbolInit() {
        barcodeParamData = appDelegate.mReader?.devicesymbolInit()! as NSArray?

        for i in 0..<barcodeParamData!.count {
            let paramValue: EAParamValue? = barcodeParamData?[i] as? EAParamValue
            tmpArray.append("\(String(describing: (paramValue?.value)!))")
        }
        
        generalOptionInit()
  
        DispatchQueue.main.async(execute: {() -> Void in
            self.optionSubTableView.reloadData()
            self.HUD.hide(true)
            self.HUD.removeFromSuperview()
        })
    }
    func generalOptionInit() {
        if self.appDelegate.mReader?.barcodedeviceget() == 0 {
            self.devicetype = 0
            let paramData = [ParamNameRedundancyLevel.rawValue, ParamNameSecurityLevel.rawValue, ParamNameInverse1D.rawValue]
            self.generalOptionParamData = self.appDelegate.mReader?.getBarcodeParam(paramData)! as NSArray?
            
        } else if self.appDelegate.mReader?.barcodedeviceget() == 2 {
            self.devicetype = 0
            let paramData = [ParamNameBiDirRedundancy.rawValue, ParamNameSecurityLevel.rawValue]
            self.generalOptionParamData = self.appDelegate.mReader?.getBarcodeParam(paramData)! as NSArray?
        } else {
            self.devicetype = 1
            let paramData =  [VideoReverse.rawValue]
            self.generalOptionParamData = self.appDelegate.mReader?.getBarcodeParam(paramData)! as NSArray?
        }
    }
    func symbolAllSetting(enable:UInt32) {
        HUD.labelText = "Saving..."
        HUD.show(true)
        navigationController?.view.addSubview(HUD)
        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            // Do something...
            var i:Int = 0
            while i < (self.barcodeParamData?.count)! {
                let paramValue: EAParamValue = (self.barcodeParamData?[i] as? EAParamValue)!
            
                switch paramValue.paramName {
                case ParamNameInverse1D:
                    paramValue.value = 0
                default:
                    paramValue.value = enable
                }
                i += 1
            }
            if self.devicetype == 0 {
                let res = self.appDelegate.mReader?.setBarcodeParam(self.barcodeParamData as! [Any])
                if (enable == 1) {
                    var data = Data()
                    data.append("F0", count: 1)
                    data.append("5800", count: 2)
                    self.appDelegate.mReader?.setBarcodeDataParam(data)
                }
                if res == ResultNoError {
                    DispatchQueue.main.async(execute: {() -> Void in
                        self.HUD.hide(true)
                        self.HUD.removeFromSuperview()
                    })
                }
                else {
                    DispatchQueue.main.async(execute: {() -> Void in
                        self.HUD.hide(true)
                        self.HUD.removeFromSuperview()
                    })
                    let alert = UIAlertView(title: "Error", message: "Failed to save", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
                    alert.show()
                }
            } else if self.devicetype == 1 {
                let res = self.appDelegate.mReader?.setBarcodeParam(self.barcodeParamData as! [Any])
                if res == ResultNoError {
                    DispatchQueue.main.async(execute: {() -> Void in
                        self.HUD.hide(true)
                        self.HUD.removeFromSuperview()
                    })
                }
                else {
                    DispatchQueue.main.async(execute: {() -> Void in
                        self.HUD.hide(true)
                        self.HUD.removeFromSuperview()
                    })
                    let alert = UIAlertView(title: "Error", message: "Failed to save", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
                    alert.show()
                }
            }
        })
    }
    func symbolDefaultAllSetting() {
        HUD = MBProgressHUD(view: navigationController?.view)
        HUD.labelText = "Saving..."
        HUD.show(true)
        navigationController?.view.addSubview(HUD)
        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            if(self.devicetype == 0){
                
                for i in 0..<self.barcodeParamData!.count{
                    let paramValue:EAParamValue = self.barcodeParamData![i] as! EAParamValue
                    switch paramValue.paramName {
                    case ParamNameUPCA:
                        paramValue.value = 1
                    case ParamNameUPCE:
                        paramValue.value = 1
                    case ParamNameUPCE1:
                        paramValue.value = 0
                    case ParamNameEAN8:
                        paramValue.value = 1
                    case ParamNameEAN13:
                        paramValue.value = 1
                    case ParamNameCode128:
                        paramValue.value = 1
                    case ParamNameCode39:
                        paramValue.value = 1
                    case ParamNameConvertCode39toCode32:
                        paramValue.value = 0
                    case ParamNameCode93:
                        paramValue.value = 0
                    case ParamNameCode11:
                        paramValue.value = 0
                    case ParamNameI2of5:
                        paramValue.value = 0
                    case ParamNameD2of5:
                        paramValue.value = 0
                    case ParamNameGS1128:
                        paramValue.value = 1
                    case ParamNameCodabar:
                        paramValue.value = 0
                    case ParamNameMSI:
                        paramValue.value = 0
                    case ParamNameC2of5:
                        paramValue.value = 0
                    case ParamNameM2of5:
                       paramValue.value = 0
                    case ParamNameK3of5:
                        paramValue.value = 0
                    case ParamNameUSPostnet:
                        paramValue.value = 0
                    case ParamNameUSPlanet:
                        paramValue.value = 0
                    case ParamNameUKPostal:
                        paramValue.value = 0
                    case ParamNameJapanPostal:
                        paramValue.value = 0
                    case ParamNameAustraliaPost:
                        paramValue.value = 0
                    case ParamNameNetherlandsKIXCode:
                        paramValue.value = 0
                    case ParamNameUSPS4CB:
                        paramValue.value = 0
                    case ParamNameUPUFICSPostal:
                        paramValue.value = 0
                    case ParamNameGS1Databar:
                        paramValue.value = 0
                    case ParamNameCompositeCCC:
                        paramValue.value = 0
                    case ParamNameCompositeCCAB:
                        paramValue.value = 0
                    case ParamNameCompositeTLC39:
                        paramValue.value = 0
                    case ParamNamePDF417:
                        paramValue.value = 1
                    case ParamNameMicroPDF417:
                        paramValue.value = 0
                    case ParamNameCode128Emul:
                        paramValue.value = 0
                    case ParamNameDataMatrix:
                        paramValue.value = 0
                    case ParamNameMaxicode:
                        paramValue.value = 0
                    case ParamNameQRCode:
                        paramValue.value = 1
                    case ParamNameMicroQR:
                        paramValue.value = 1
                    case ParamNameAztec:
                        paramValue.value = 1
                    case ParamNameHanXin:
                        paramValue.value = 0
                    default:
                        break
                    }
                }
            } else if(self.devicetype == 1){
                for i in 0..<self.barcodeParamData!.count{
                    let paramValue:EAParamValue = self.barcodeParamData![i] as! EAParamValue
                    switch(paramValue.paramName) {
                    case UPCA:
                        paramValue.value = 1
                    case UPCE0:
                        paramValue.value = 1
                    case UPCE1:
                        paramValue.value = 0
                    case EAN8:
                        paramValue.value = 1
                    case EAN13:
                        paramValue.value = 1
                    case Code128:
                        paramValue.value = 1
                    case Code39:
                        paramValue.value = 1
                    case Code39Pharmaceutical:
                        paramValue.value = 0
                    case Code93:
                        paramValue.value = 1
                    case Code11:
                        paramValue.value = 0
                    case I2of5:
                        paramValue.value = 1
                    case Codabar:
                        paramValue.value = 1
                    case IsbnTranslate:
                        paramValue.value = 0
                    case MSI:
                        paramValue.value = 0
                    case X2of5:
                        paramValue.value = 0
                    case PDF417:
                        paramValue.value = 1
                    case MacroPDF417:
                        paramValue.value = 1
                    case MicroPDF:
                        paramValue.value = 0
                    case Matrix:
                        paramValue.value = 0
                    case MaxiCode:
                        paramValue.value = 1
                    case QRCode:
                        paramValue.value = 1
                    case AztecCode:
                        paramValue.value = 1
                    case NEC2of5:
                        paramValue.value = 1
                    case R2of5:
                        paramValue.value = 0
                    case A2of5:
                        paramValue.value = 0
                    case GS1128:
                        paramValue.value = 1
                    case Telepen:
                        paramValue.value = 0
                    case RSS14:
                        paramValue.value = 1
                    case RSSLimit:
                        paramValue.value = 0
                    case RSSExp:
                        paramValue.value = 0
                    case TriopticCode:
                        paramValue.value = 0
                    case CodablockA:
                        paramValue.value = 0
                    case CodablockF:
                        paramValue.value = 0
                    case ComCode:
                        paramValue.value = 1
                    case TLC39:
                        paramValue.value = 0
                    case ChinaPost:
                        paramValue.value = 0
                    case KoreaPost:
                        paramValue.value = 0
                    case PostalCodes:
                        paramValue.value = 0
                    case HanXinCode:
                        paramValue.value = 0
                    default:
                        break
                    }
                    
                }
            }
            
            let res = (self.appDelegate.mReader?.setBarcodeParam(self.barcodeParamData as! [Any]))
            if(res == ResultNoError){
                DispatchQueue.main.async(execute: {() -> Void in
                    self.HUD.hide(true)
                    self.HUD.removeFromSuperview()
                })
            } else {
                DispatchQueue.main.async(execute: {() -> Void in
                    self.HUD.hide(true)
                    self.HUD.removeFromSuperview()
                })
                let dialog = UIAlertController(title: "Error", message: "Failed to save", preferredStyle: .alert)
                let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
                dialog.addAction(action)
                self.present(dialog, animated: true, completion: nil)
            }
        })
    }
    
    func hideViews() {
//        optionPickerView.isHidden = true
        optionTopView.isHidden = true
        optionSubTableView.isHidden = true
        charsetTopView.isHidden = true
        generalOptionTableView.isHidden = true
        generalOptionTopView.isHidden = true
        generalOptionPickerView.isHidden = true
    }
    @objc func symboldetail (_ gestureRecognizer: UILongPressGestureRecognizer) {
        let p: CGPoint = gestureRecognizer.location(in: optionSubTableView)
        let indexPath: IndexPath? = optionSubTableView.indexPathForRow(at: p)
        selectedcell = (indexPath?.row)!
        if devicetype == 1 {
            if (selectedcell == 2) || (selectedcell == 7) || (selectedcell == 12) || (selectedcell == 16) || (selectedcell == 26) || (selectedcell == 27) || (selectedcell == 32) {
                
            }
            else if selectedcell < 37 {
                if isShowingAlert == false {
                    isShowingAlert = true
                    performSegue(withIdentifier: "SymbolDetail", sender: indexPath)
                }
            }
            else {

            }
        } else {
            if appDelegate.mReader?.barcodedeviceget() == 2 {
                if selectedcell < 5 {
                    if isShowingAlert == false {
                        isShowingAlert = true
                        performSegue(withIdentifier: "symbolZsetting", sender: indexPath)
                    }
                }
                else if (selectedcell == 13) || (selectedcell == 15) {
                    
                }
                else if (selectedcell > 4) && (selectedcell < 15) {
                    if isShowingAlert == false {
                        isShowingAlert = true
                        performSegue(withIdentifier: "symbolZsetting", sender: indexPath)
                    }
                }
                else if (selectedcell > 15) && (selectedcell < 18) {
                    if isShowingAlert == false {
                        isShowingAlert = true
                        performSegue(withIdentifier: "symbolZsetting", sender: indexPath)
                    }
                }
            } else {
                if selectedcell < 5 {
                    if isShowingAlert == false {
                        isShowingAlert = true
                        performSegue(withIdentifier: "symbolZsetting", sender: indexPath)
                    }
                } else if (selectedcell == 13) || (selectedcell == 15) || (selectedcell == 16) || (selectedcell == 19) || (selectedcell == 28) || (selectedcell == 29) || (selectedcell == 30) || (selectedcell == 32) || (selectedcell == 34) {
                    
                } else if (selectedcell > 20) && (selectedcell < 24) {
                    
                } else if (selectedcell > 4) && (selectedcell < 15) {
                    if isShowingAlert == false {
                        isShowingAlert = true
                        performSegue(withIdentifier: "symbolZsetting", sender: indexPath)
                    }
                } else if (selectedcell > 15) && (selectedcell < 38) {
                    if isShowingAlert == false {
                        isShowingAlert = true
                        performSegue(withIdentifier: "symbolZsetting", sender: indexPath)
                    }
                } else {
                    
                }
            }
        }
    }
    @IBAction func topviewOK(_ sender: UIButton) {
        HUD = MBProgressHUD(view: navigationController?.view)
        HUD.labelText = "Saving..."
        HUD.show(true)
        navigationController?.view.addSubview(HUD)
        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            // Do something...
            var i = 0
            while i < (self.barcodeParamData?.count)! {
                let tempValue: EAParamValue? = self.barcodeParamData?[i] as? EAParamValue
                tempValue?.value = UInt32(self.tmpArray[i])!
                print("SAVE [\(i)] tempValue.value = \(String(describing: tempValue?.value))")
                print("topviewOK  self.tmpArray [\(i)]  = \(self.tmpArray[i])")
                i += 1
            }
            
            self.appDelegate.mReader?.setBarcodeParam(self.barcodeParamData as! [Any])
            DispatchQueue.main.async(execute: {() -> Void in
                self.HUD.hide(true)
                self.HUD.removeFromSuperview()
                self.hideViews()
            })
        })
//        self.hideViews()
        
    }
    @IBAction func topviewCancel(_ sender: UIButton) {
            hideViews()
    }
    @IBAction func charsetTopViewDone(_ sender: UIButton) {
        hideViews()
    }
    @IBAction func generalTopViewCancel(_ sender: UIButton) {
        if pickerviewflag == false {
            hideViews()
        } else {
            generalOptionPickerView.isHidden = true
            pickerviewflag = false
        }
    }
    @IBAction func generalTopViewOK(_ sender: UIButton) {
        if pickerviewflag == false {

            let res = appDelegate.mReader?.setBarcodeParam(generalOptionParamData as! [Any])
            if res == ResultNoError {
                let dialog = UIAlertController(title: "Success", message: "Saved successfully", preferredStyle: .alert)
                let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
                dialog.addAction(action)
                self.present(dialog, animated: true, completion: nil)
            } else {
                let dialog = UIAlertController(title: "Error", message: "Failed to save", preferredStyle: .alert)
                let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
                dialog.addAction(action)
                self.present(dialog, animated: true, completion: nil)
            }
            hideViews()
        } else {
            let idx = Int(generalOptionPickerView.selectedRow(inComponent: 0))
            if generalOptionPickerView.tag == PICKER_VIEW_REDUNDANCY_LEVEL {
                let paramValue = generalOptionParamData![topviewflag] as? EAParamValue
                if appDelegate.mReader?.barcodedeviceget() == 0 {
                    paramValue?.value = (UInt32(idx) + 1)
                }
                else {
                    paramValue?.value = UInt32(idx)
                }
            }
            else if generalOptionPickerView.tag == PICKER_VIEW_SECURITY_LEVEL {
                let paramValue = generalOptionParamData![topviewflag] as? EAParamValue
                paramValue?.value = UInt32(idx)
            } else if generalOptionPickerView.tag == PICKER_VIEW_1D_INVERSE {
               let paramValue = generalOptionParamData![topviewflag] as? EAParamValue
                paramValue?.value = UInt32(idx)
          
            }
            else if generalOptionPickerView.tag == PICKER_VIEW_VIDEO_REVERSE {
                let paramValue = generalOptionParamData![topviewflag] as? EAParamValue
                paramValue?.value = UInt32(idx)
            }
            generalOptionTableView.reloadData()
            generalOptionPickerView.isHidden = true
            pickerviewflag = false
        }
    }
    @objc func bluetoothDisconnected(_ notification: Notification){
        HUD.hide(true)
        HUD.removeFromSuperview()
        DispatchQueue.main.async(execute: {() -> Void in
            self.appDelegate.mPeripheral = nil
            self.performSegue(withIdentifier: "Barcode", sender: nil)
        })
    }
}
