//
//  SelectionMaskEditViewController.swift
//  Inventory_ATx88
//
//  Created by 류은주 on 2018. 1. 4..
//  Copyright © 2018년 류은주. All rights reserved.
//
let PICKER_VIEW_TARGET = 0
let PICKER_VIEW_ACTION = 1
let PICKER_VIEW_BANK = 2
let PICKER_VIEW_OFFSET = 3

import UIKit

class SelectionMaskEditViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate, EAReaderDelegate{
    @IBOutlet weak var targetTextField: UITextField!
    @IBOutlet weak var actionTextField: UITextField!
    @IBOutlet weak var bankTextField: UITextField!
    @IBOutlet weak var offsetTextField: UITextField!
    @IBOutlet weak var maskTextField: UITextField!
    @IBOutlet weak var lengthTextField: UITextField!
    @IBOutlet weak var pickerView: UIPickerView!
    @IBOutlet weak var topView: UIView!
    @IBOutlet weak var shadowView: UIView!
    
    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    var selectMaskParam: EASelectMaskParam?
    var targetindex: Int = 0
    var actionindex: Int = 0
    var bankindex: Int = 0
    var offsetvalue: Int = 0
    var offsetText = ""
    var maskstring = ""
    var lengthvalue: Int = 0
    var alert: UIAlertView?
    var targetPickerData: NSArray = ["S0", "S1", "S2", "S3", "SL"]
    var actionPickerData: NSArray = ["AB", "AN", "NB", "MN", "BA", "BN", "NA", "NM"]
    var bankPickerData: NSArray = ["Reserved", "EPC", "TID", "User"]
    var bit_PickerData: NSArray = ["0", "16", "32", "48", "64", "80", "96", "112", "128", "144", "160", "176", "192", "208", "224", "240"]
    var offsetPickerData: NSArray?

    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)
        if selectMaskParam != nil {
            setTarget(Int((selectMaskParam?.target)!.rawValue))
            setAction(Int((selectMaskParam?.action)!.rawValue))
            setBank(Int(selectMaskParam!.bank.rawValue))
            setOffset(getBitDataIndex(Int((selectMaskParam?.offset)!)))
            setMask((selectMaskParam?.mask)!)
            setLength("\(String(describing: (selectMaskParam?.length)!))")
        }
        else {
            // Initialization
            setTarget(Int(MaskTarget_SL.rawValue))
            setAction(Int(MaskAction_AB.rawValue))
            setBank(Int(Bank_EPC.rawValue))
            setOffset(1)
            // 16 bit
            setMask("")
            setLength("16")
            // 16 bit
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "BluetoothDisconnected"), object: nil)
    }
    
    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
        if (identifier == "BackToSource") {
            // validation
//            let maskBit: Int = Int(lengthTextField.text)
            print("maskstring.lengthOfBytes(using: String.Encoding.utf8) \(maskstring.lengthOfBytes(using: String.Encoding.utf8))")
            selectMaskParam?.target = MaskTargetType(rawValue: MaskTargetType.RawValue(targetindex))
            selectMaskParam?.action = MaskActionType(rawValue: MaskActionType.RawValue(actionindex))
            selectMaskParam?.bank = BankType(rawValue: BankType.RawValue(bankindex))
            selectMaskParam?.offset = Int32(offsetvalue)
            selectMaskParam?.mask = maskstring
            if(lengthvalue > (maskstring.lengthOfBytes(using: String.Encoding.utf8)*4)){
                selectMaskParam?.length = (Int32(maskstring.lengthOfBytes(using: String.Encoding.utf8)*4))
                lengthvalue = (maskstring.lengthOfBytes(using: String.Encoding.utf8)*4)
            } else {
                selectMaskParam?.length = Int32(lengthvalue)
            }
        }
        return true
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let nonHex = CharacterSet(charactersIn: "0123456789ABCDEFabcdef").inverted
        let nonHexRange: NSRange = (string as NSString).rangeOfCharacter(from: nonHex)
        let isHex: Bool = nonHexRange.location == NSNotFound
        if isHex {
            let newString: String? = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
            textField.text = newString?.uppercased()
        }
        return false
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if(pickerView.tag == PICKER_VIEW_TARGET){
            return (targetPickerData.count)
        } else if(pickerView.tag == PICKER_VIEW_ACTION){
            return (actionPickerData.count)
        } else if(pickerView.tag == PICKER_VIEW_BANK){
            return (bankPickerData.count)
        } else if(pickerView.tag == PICKER_VIEW_OFFSET){
            return (bit_PickerData.count)
        } else {
            return (bit_PickerData.count)
        }
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if(pickerView.tag == PICKER_VIEW_TARGET){
            return targetPickerData.object(at: row) as? String
        } else if(pickerView.tag == PICKER_VIEW_ACTION){
            return actionPickerData.object(at: row) as? String
        } else if(pickerView.tag == PICKER_VIEW_BANK){
            return bankPickerData.object(at: row) as? String
        }else if(pickerView.tag == PICKER_VIEW_OFFSET){
            return bit_PickerData.object(at: row) as? String
        }else {
            return targetPickerData.object(at: row) as? String
        }
    }
    
    
    func setTarget(_ index: Int) {
        targetTextField.text = targetPickerData[index] as? String
        targetindex = Int(index)
    }
    
    func setAction(_ index: Int) {
        actionTextField.text = actionPickerData[index] as? String
        actionindex = Int(index)
    }
    
    func setBank(_ index: Int) {
        bankTextField.text = bankPickerData[index] as? String
        bankindex = Int(index)
    }
    
    func setOffset(_ index: Int) {
        offsetText = (bit_PickerData[index] as? String)!
        offsetTextField.text = "\(offsetText) bit"
        offsetvalue = ((bit_PickerData[index] as AnyObject).integerValue)!
    }
    
    func setMask(_ mask: String) {
        maskTextField.text = mask
        maskstring = mask
    }
    
    func setLength(_ length: String) {
        lengthTextField.text = "\(length) bit"
        lengthvalue = Int(length) ?? 0
    }
    func getBitDataIndex(_ bit: Int) -> Int {
        return bit_PickerData.index(of: "\(Int(bit))")
    }
    func hidePickerView(){
        topView.isHidden = true
        pickerView.isHidden = true
//        shadowView.isHidden = true
    }
    func showPickerView(){
        topView.isHidden = false
        pickerView.isHidden = false
//        shadowView.isHidden = false
    }
    
    @IBAction func targetBtnTapped(_ sender: UIButton) {
        pickerView.tag = PICKER_VIEW_TARGET
        pickerView.reloadAllComponents()
        
        if !(targetTextField.text == ""){
            pickerView.selectRow(targetPickerData.index(of: targetTextField.text!), inComponent: 0, animated: false)
        }
        else {
            pickerView.selectRow(0, inComponent: 0, animated: false)
        }
        showPickerView()
    }
    @IBAction func actionBtnTapped(_ sender: UIButton) {
        pickerView.tag = PICKER_VIEW_ACTION
        pickerView.reloadAllComponents()
        
        if !(actionTextField.text == ""){
            pickerView.selectRow(actionPickerData.index(of: actionTextField.text!), inComponent: 0, animated: false)
        }
        else {
            pickerView.selectRow(0, inComponent: 0, animated: false)
        }
        showPickerView()
    }
    @IBAction func bankBtnTapped(_ sender: UIButton) {
        pickerView.tag = PICKER_VIEW_BANK
        pickerView.reloadAllComponents()
        
        if !(bankTextField.text == ""){
            pickerView.selectRow(bankPickerData.index(of: bankTextField.text!), inComponent: 0, animated: false)
        }
        else {
            pickerView.selectRow(0, inComponent: 0, animated: false)
        }
        showPickerView()
    }
    @IBAction func offsetBtnTapped(_ sender: UIButton) {
        pickerView.tag = PICKER_VIEW_OFFSET
        pickerView.reloadAllComponents()
        
        if !(offsetTextField.text == ""){
            pickerView.selectRow(bit_PickerData.index(of: offsetText), inComponent: 0, animated: false)
        }
        else {
            pickerView.selectRow(0, inComponent: 0, animated: false)
        }
        showPickerView()
    }
    @IBAction func maskBtnTapped(_ sender: UIButton) {
        let alert = UIAlertController(title: "Mask:", message:"Please enter mask value.", preferredStyle: .alert)
        alert.addTextField(configurationHandler: {(_ textField: UITextField) -> Void in textField.keyboardType = .alphabet; textField.delegate = self as UITextFieldDelegate})
        let ok = UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
            let textField: UITextField? = alert.textFields?.first
            self.maskTextField.text = textField!.text
            self.maskstring = textField!.text!
            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 lengthBtnTapped(_ sender: UIButton) {
        let alert = UIAlertController(title: "Length:", message:"Please enter length 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.lengthTextField.text = "\(Int32(Int(textField!.text ?? "") ?? 0)) bit"
            self.lengthvalue = Int(textField!.text!)!
            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 cancelTapped(_ sender: UIButton) {
        hidePickerView()
    }
    
    @IBAction func okTapped(_ sender: UIButton) {
        let idx = pickerView.selectedRow(inComponent: 0)
        if(pickerView.tag == PICKER_VIEW_TARGET){
            setTarget(idx)
        } else if(pickerView.tag == PICKER_VIEW_ACTION){
            setAction(idx)
        } else if(pickerView.tag == PICKER_VIEW_BANK){
            setBank(idx)
        }else if(pickerView.tag == PICKER_VIEW_OFFSET){
           setOffset(idx)
        }else {
            
        }
        hidePickerView()
    }
    @objc func bluetoothDisconnected(_ notification: Notification){
        //        let dialog = UIAlertController(title: "Connect State", message: "BT Disconnected!!!", preferredStyle: .alert)
        //        let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
        //        dialog.addAction(action)
        //        self.present(dialog, animated: true, completion: nil)
        DispatchQueue.main.async(execute: {() -> Void in
            self.appDelegate.mPeripheral = nil
            self.appDelegate.connectflag = false
            self.performSegue(withIdentifier: "ReadMemory", sender: nil)
        })
    }
}
