//
//  ReadMemoryViewController.swift
//  ReadMemory_EAReader
//
//  Created by 류은주 on 2018. 1. 11..
//  Copyright © 2018년 류은주. All rights reserved.
//
let READ_PICKER_VIEW_BANK = 0
let READ_PICKER_VIEW_OFFSET = 1
let READ_PICKER_VIEW_LENGTH = 2

let MSG_TAG_WAIT = "Tag memory to Access. Click the button."

import UIKit

class LockMemoryViewController: UIViewController, UITextFieldDelegate, EAReaderDelegate {

    @IBOutlet weak var connectBarItem: UIBarButtonItem!
    @IBOutlet weak var optionBarItem: UIBarButtonItem!

    @IBOutlet weak var readResult: UILabel!
    @IBOutlet weak var epcData: UILabel!
    @IBOutlet weak var rssiData: UILabel!
    @IBOutlet weak var phaseData: UILabel!
    @IBOutlet weak var blockView: UIView!
    
    @IBOutlet weak var killpasswordBtn: UIButton!
    @IBOutlet weak var accesspasswordBtn: UIButton!
    @IBOutlet weak var epcBtn: UIButton!
    @IBOutlet weak var tidBtn: UIButton!
    @IBOutlet weak var userBtn: UIButton!
    @IBOutlet weak var passwordBtn: UIButton!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var lockBtn: UIButton!
    @IBOutlet weak var unlockBtn: UIButton!
    @IBOutlet weak var permalockBtn: UIButton!
    
    var appDelegate = UIApplication.shared.delegate as! AppDelegate

    var bankValue = 1
    var offsetValue = 2
    var lengthValue = 2
    var passwordValue = ""
    var writedataValue = ""
    
    var notiAlert: UIAlertController?
    
    var isActionResult = false
    
    var opmode = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            // Do something...
            if self.appDelegate.mReader == nil {
                return
            }
            self.appDelegate.mReader?.continuousMode = false
            DispatchQueue.main.async(execute: {() -> Void in
                self.killpasswordBtn.backgroundColor = UIColor.lightGray
                self.killpasswordBtn.setTitleColor(UIColor.gray, for: .normal)
                self.accesspasswordBtn.backgroundColor = UIColor.lightGray
                self.accesspasswordBtn.setTitleColor(UIColor.gray, for: .normal)
                self.epcBtn.backgroundColor = UIColor.lightGray
                self.epcBtn.setTitleColor(UIColor.gray, for: .normal)
                self.tidBtn.backgroundColor = UIColor.lightGray
                self.tidBtn.setTitleColor(UIColor.gray, for: .normal)
                self.userBtn.backgroundColor = UIColor.lightGray
                self.userBtn.setTitleColor(UIColor.gray, for: .normal)
                self.lockBtn.setImage(UIImage(named: "lock_on.png"), for: .normal)
                self.unlockBtn.setImage(UIImage(named: "unlocked_off.png"), for: .normal)
                self.permalockBtn.setImage(UIImage(named: "permalock_off.png"), for: .normal)
            })
        })
       
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        appDelegate.mReader?.setDelegate(self)
        let center = NotificationCenter.default
        center.addObserver(self, selector: #selector(bluetoothDisconnected), name: NSNotification.Name.init(rawValue: "BluetoothDisconnected"), object: nil)
        if appDelegate.connectflag == true {
            connectBarItem.title = "Cancel"
            optionBarItem.isEnabled = true
            blockView.isHidden = true
            appDelegate.mReader?.setTagDataType(TAG_DATA_TYPE_ASCII)
        } else {
            connectBarItem.title = "Search"
            optionBarItem.isEnabled = false
            blockView.isHidden = false
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if appDelegate.mReader?.getAction() != CommandStop {
            appDelegate.mReader?.stop()
        }
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "BluetoothDisconnected"), object: nil)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @objc func changedActionState(_ action: CommandType) {
        if action == CommandStop {
            notiAlert?.dismiss(animated: true) {() -> Void in }
            if isActionResult == false {
                epcData.text = MSG_TAG_WAIT
                readResult.text = "Fail to get a data"
                rssiData.text = String(format: "%.1f dB", 0.0)
                phaseData.text = String(format: "%.1f˚", 0.0)
            }
        }
        
        if action == CommandStop {
            notiAlert?.dismiss(animated: true) {() -> Void in }
            if isActionResult == false {
                epcData.text = MSG_TAG_WAIT
                readResult.text = "Fail to set lock"
            }
        }
        else {
            notiAlert = UIAlertController(title: "On progress", message:"Waiting Tag Memory", preferredStyle: .alert)
            
            let ok = UIAlertAction(title: "Stop", style: .default, handler: {(_ action: UIAlertAction) -> Void in
                
                //self.appDelegate.mReader?.stop
                self.notiAlert?.dismiss(animated: true) {() -> Void in}
            })
            
            notiAlert?.addAction(ok)
            
            DispatchQueue.main.async(execute: {() -> Void in
                self.present(self.notiAlert!, animated: true) {() -> Void in }
            })
        }
    }
    @objc func tagAccessResult(_ error: ResultType, actionState action: CommandType, epc: String, data: String, rssi: Float, phase: Float) {
        print("RMV - Access Result : \(error), \(action), \(epc), \(data), \(rssi), \(phase)")

        isActionResult = true
        if error != ResultNoError {
            notiAlert?.dismiss(animated: true) {() -> Void in }
            epcData.text = MSG_TAG_WAIT
            readResult.text = EAResultType.msg(error)
            rssiData.text = String(format: "%.1f dB", 0.0)
            phaseData.text = String(format: "%.1f˚", 0.0)
            
            let alert = UIAlertController(title: "Error", message:EAResultType.msg(error), preferredStyle: .alert)
            
            let ok = UIAlertAction(title: "OK", style: .default, handler: {(_ action: UIAlertAction) -> Void in
                alert.dismiss(animated: true) {() -> Void in}
            })
            
            alert.addAction(ok)
            
            DispatchQueue.main.async(execute: {() -> Void in
                self.present(alert, animated: true) {() -> Void in }
            })
            return
        }
        epcData.text = epc
        readResult.text = "Success"
        rssiData.text = String(format: "%.1f dB", rssi)
        phaseData.text = String(format: "%.1f˚", phase)
        notiAlert?.dismiss(animated: true) {() -> Void in }
        
    }

    func cleanData() {
        readResult.text = "Result"
        epcData.text = "Tag Memory to Access. Click the button"
        rssiData.text = "0.0 dB"
        phaseData.text = "0.0˚"
    }
    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
    }
    func lockAction() {
        isActionResult = false
        appDelegate.mReader?.accessPassword = passwordTextField.text
        let param = LockParam()
        if killpasswordBtn.backgroundColor == UIColor.magenta {
            param.killPassword = true
        }
        else {
            param.killPassword = false
        }
        if accesspasswordBtn.backgroundColor == UIColor.magenta {
            param.accessPassword = true
        }
        else {
            param.accessPassword = false
        }
        if epcBtn.backgroundColor == UIColor.magenta {
            param.epc = true
        }
        else {
            param.epc = false
        }
        if tidBtn.backgroundColor == UIColor.magenta {
            param.tid = true
        }
        else {
            param.tid = false
        }
        if userBtn.backgroundColor == UIColor.magenta {
            param.user = true
        }
        else {
            param.user = false
        }
        if appDelegate.mReader?.lock(param) != ResultNoError {
            print("ERROR. Failed to start lock tag")
        }
    }
    func unlockAction() {
        isActionResult = false
        appDelegate.mReader?.accessPassword = passwordTextField.text
        let param = LockParam()
        if killpasswordBtn.backgroundColor == UIColor.magenta {
            param.killPassword = true
        }
        else {
            param.killPassword = false
        }
        if accesspasswordBtn.backgroundColor == UIColor.magenta {
            param.accessPassword = true
        }
        else {
            param.accessPassword = false
        }
        if epcBtn.backgroundColor == UIColor.magenta {
            param.epc = true
        }
        else {
            param.epc = false
        }
        if tidBtn.backgroundColor == UIColor.magenta {
            param.tid = true
        }
        else {
            param.tid = false
        }
        if userBtn.backgroundColor == UIColor.magenta {
            param.user = true
        }
        else {
            param.user = false
        }
        if appDelegate.mReader?.unlock(param) != ResultNoError {
            print("ERROR. Failed to start unlock tag")
        }
    }
    func permalockAction() {
        isActionResult = false
        appDelegate.mReader?.accessPassword = passwordTextField.text
        let param = LockParam()
        if killpasswordBtn.backgroundColor == UIColor.magenta {
            param.killPassword = true
        }
        else {
            param.killPassword = false
        }
        if accesspasswordBtn.backgroundColor == UIColor.magenta {
            param.accessPassword = true
        }
        else {
            param.accessPassword = false
        }
        if epcBtn.backgroundColor == UIColor.magenta {
            param.epc = true
        }
        else {
            param.epc = false
        }
        if tidBtn.backgroundColor == UIColor.magenta {
            param.tid = true
        }
        else {
            param.tid = false
        }
        if userBtn.backgroundColor == UIColor.magenta {
            param.user = true
        }
        else {
            param.user = false
        }
        if appDelegate.mReader?.permaLock(param) != ResultNoError {
            print("ERROR. Failed to start permalock tag")
        }
    }
    @IBAction func connectBarItemTapped(_ sender: UIBarButtonItem) {
        if(appDelegate.connectflag == false){
            performSegue(withIdentifier: "bleconnect", sender: nil)
        } else {
            appDelegate.connectflag = false
            if appDelegate.mReader != nil {
                appDelegate.mReader?.disconnect()
                appDelegate.mReader = nil
            }
            if appDelegate.mPeripheral != nil {
                appDelegate.mCentralManager?.cancelPeripheralConnection(appDelegate.mPeripheral!)
                appDelegate.mPeripheral = nil
            }
            viewWillAppear(true)
        }
        
    }
    
    @IBAction func optionBarItemTapped(_ sender: UIBarButtonItem) {
        performSegue(withIdentifier: "OptionView", sender: nil)
    }
    
    @IBAction func killpasswordBtnTapped(_ sender: UIButton) {
        if killpasswordBtn.backgroundColor == UIColor.magenta {
            killpasswordBtn.backgroundColor = UIColor.lightGray
            killpasswordBtn.setTitleColor(UIColor.gray, for: .normal)
        }
        else {
            killpasswordBtn.backgroundColor = UIColor.magenta
            killpasswordBtn.setTitleColor(UIColor.blue, for: .normal)
        }
    }
   
    @IBAction func accesspasswordBtnTapped(_ sender: UIButton) {
        if accesspasswordBtn.backgroundColor == UIColor.magenta {
            accesspasswordBtn.backgroundColor = UIColor.lightGray
            accesspasswordBtn.setTitleColor(UIColor.gray, for: .normal)
        }
        else {
            accesspasswordBtn.backgroundColor = UIColor.magenta
            accesspasswordBtn.setTitleColor(UIColor.blue, for: .normal)
        }
    }
    @IBAction func epcBtnTapped(_ sender: UIButton) {
        if epcBtn.backgroundColor == UIColor.magenta {
            epcBtn.backgroundColor = UIColor.lightGray
            epcBtn.setTitleColor(UIColor.gray, for: .normal)
        }
        else {
            epcBtn.backgroundColor = UIColor.magenta
            epcBtn.setTitleColor(UIColor.blue, for: .normal)
        }

    }
    @IBAction func tidBtnTapped(_ sender: UIButton) {
        if tidBtn.backgroundColor == UIColor.magenta {
            tidBtn.backgroundColor = UIColor.lightGray
            tidBtn.setTitleColor(UIColor.gray, for: .normal)
        }
        else {
            tidBtn.backgroundColor = UIColor.magenta
            tidBtn.setTitleColor(UIColor.blue, for: .normal)
        }
    }
    @IBAction func userBtnTapped(_ sender: UIButton) {
        if userBtn.backgroundColor == UIColor.magenta {
            userBtn.backgroundColor = UIColor.lightGray
            userBtn.setTitleColor(UIColor.gray, for: .normal)
        }
        else {
            userBtn.backgroundColor = UIColor.magenta
            userBtn.setTitleColor(UIColor.blue, for: .normal)
        }
    }
    @IBAction func lockBtnTapped(_ sender: UIButton) {
        opmode = 0
        lockBtn.setImage(UIImage(named: "lock_on.png"), for: .normal)
        unlockBtn.setImage(UIImage(named: "unlocked_off.png"), for: .normal)
        permalockBtn.setImage(UIImage(named: "permalock_off.png"), for: .normal)
    }
    @IBAction func unlockBtnTapped(_ sender: UIButton) {
        opmode = 1
        lockBtn.setImage(UIImage(named: "locked-off.png"), for: .normal)
        unlockBtn.setImage(UIImage(named: "unlock_on.png"), for: .normal)
        permalockBtn.setImage(UIImage(named: "permalock_off.png"), for: .normal)
    }
    @IBAction func permalockBtnTapped(_ sender: UIButton) {
        opmode = 2
        lockBtn.setImage(UIImage(named: "locked-off.png"), for: .normal)
        unlockBtn.setImage(UIImage(named: "unlocked_off.png"), for: .normal)
        permalockBtn.setImage(UIImage(named: "permalock_on.png"), for: .normal)
    }
    
    @IBAction func passwordBtnTapped(_ sender: UIButton) {
        let alert = UIAlertController(title: "Password", message:"Please enter Password", 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.passwordValue = (textField?.text)!
            self.passwordTextField.text = self.passwordValue
            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 startBtnTapped(_ sender: UIButton) {
        if opmode == 0 {
            lockAction()
        }
        else if opmode == 1 {
            unlockAction()
        }
        else {
            permalockAction()
        }
    }
    @IBAction func clearBtnTapped(_ sender: UIButton) {
       cleanData()
    }
    @objc func bluetoothDisconnected(_ notification: Notification){
        appDelegate.mReader = nil
        appDelegate.mPeripheral = nil
        appDelegate.connectflag = false
        let dialog = UIAlertController(title: "Connect State", message: "BT Disconnected!!!", preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
        dialog.addAction(action)
        self.present(dialog, animated: true, completion: nil)

         viewWillAppear(true)
    }
    /*
    // 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.
    }
    */

}
