//
//  SelectionMaskViewController.swift
//  Inventory_ATx88
//
//  Created by 류은주 on 2018. 1. 3..
//  Copyright © 2018년 류은주. All rights reserved.
//

import UIKit

class SelectionMaskViewController: UIViewController, UITableViewDataSource,  UITableViewDelegate, EAReaderDelegate {

    @IBOutlet weak var maskTableView: UITableView!
    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    var checklist = [AnyHashable]()
    var checkarray = [AnyHashable]()
    var deletearray = [AnyHashable]()
    var maskData = [AnyHashable]()
    var arrayIndex: Int?
    var selectedcell = 0
    var isEditCell = false
    let targetdata: NSArray = ["S0", "S1", "S2", "S3", "SL"]
    
    var HUD = MBProgressHUD()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.HUD = MBProgressHUD(view: self.navigationController?.view)
        self.HUD.labelText = "Loading..."
        self.HUD.show(true)
        self.navigationController?.view.addSubview(self.HUD)
        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            self.initLoadMask()
        })
    }
    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.
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "MaskEdit") {
            print("SelectionMaskCell")
            let vc = segue.destination as? SelectionMaskEditViewController
            //        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
            if selectedcell < deletearray.count {
//                vc.selectMaskParam = deletearray[selectedcell]
                vc?.selectMaskParam = deletearray[selectedcell] as? EASelectMaskParam
                isEditCell = true
            }
            if (selectedcell >= deletearray.count)  {
                vc?.selectMaskParam  = EASelectMaskParam()
                vc?.selectMaskParam?.target = MaskTarget_SL
                vc?.selectMaskParam?.action = MaskAction_AB
                vc?.selectMaskParam?.bank = Bank_EPC
                vc?.selectMaskParam?.offset = 16
                vc?.selectMaskParam?.mask = ""
                vc?.selectMaskParam?.length = 16
            }
        }
    }
    @IBAction func prepare(forUnwind segue: UIStoryboardSegue) {
        let sourceViewController = segue.source as? SelectionMaskEditViewController
        print("\(String(describing: sourceViewController?.selectMaskParam))")
        if isEditCell == false {
            //[self initLoadMask];
            maskData.append((sourceViewController?.selectMaskParam!)!)
            checklist.append((sourceViewController?.selectMaskParam!)!)
            deletearray.append((sourceViewController?.selectMaskParam)!)
        }
        maskTableView.reloadData()
    }
    /*
    // 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 numberOfSections(in tableView: UITableView) -> Int {
        // Return the number of sections.
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section.
        return 8
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "SelectionMaskCell", for: indexPath) as? SelectionMaskTableViewCell
        
         let cell : SelectionMaskTableViewCell = tableView.dequeueReusableCell(withIdentifier: "SelectionMaskCell", for: indexPath) as! SelectionMaskTableViewCell
        if indexPath.row < deletearray.count {
            let maskParam: EASelectMaskParam? = deletearray[indexPath.row] as? EASelectMaskParam
            cell.targetLabel.text = DATA_TARGET[Int(Float((((maskParam?.target))?.rawValue)!))]
//            cell.targetLabel.text = "\(String(describing: (maskParam?.target)!))"
            cell.actionLabel.text = EAMaskActionType.toString((maskParam?.action)!, targetType: (maskParam?.target)!)
            cell.bankLabel.text = DATA_BANK[Int(Float((((maskParam?.bank))?.rawValue)!))]
//            cell.bankLabel.text = "\(String(describing: (maskParam?.bank)!))"
            cell.offsetLabel.text = "\(String(describing: (maskParam?.offset)!)) bit"
            cell.lengthLabel.text = "\(String(describing: (maskParam?.length)!)) bit"
            cell.maskLabel.text = maskParam?.mask

            arrayIndex = indexPath.row
            let checkParam: EASelectMaskParam? = deletearray[indexPath.row] as? EASelectMaskParam
            if checkParam?.used == true {
                cell.accessoryType = .checkmark
            }
            else {
                cell.accessoryType = .none
            }
        }else {
            cell.targetLabel.text = "SL"
            cell.actionLabel.text = """
            Matching is Assert SL
            Not-Matching is Deassert SL
            """
            cell.bankLabel.text = "EPC"
            cell.offsetLabel.text = "16 bit"
            cell.lengthLabel.text = "16 bit"
            cell.maskLabel.text = " "
            cell.accessoryType = .none
        }
        let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.selectmaskdelete))
        recognizer.minimumPressDuration = 1.0
        //seconds
        cell.addGestureRecognizer(recognizer)
        return cell
        }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as? SelectionMaskTableViewCell
        if indexPath.row < deletearray.count {
            if cell?.accessoryType == .checkmark {
                cell?.accessoryType = .none
                let replaceParam: EASelectMaskParam? = deletearray[indexPath.row] as? EASelectMaskParam
                replaceParam?.used = false
                checklist[indexPath.row] = replaceParam ?? EASelectMaskParam()
                deletearray[indexPath.row] = replaceParam ?? EASelectMaskParam()
                maskData[indexPath.row] = replaceParam ?? EASelectMaskParam()
            }
            else {
                cell?.accessoryType = .checkmark
                let replaceParam: EASelectMaskParam? = deletearray[indexPath.row] as? EASelectMaskParam
                replaceParam?.used = true
                checklist[indexPath.row] = replaceParam ?? EASelectMaskParam()
                deletearray[indexPath.row] = replaceParam ?? EASelectMaskParam()
                maskData[indexPath.row] = replaceParam ?? EASelectMaskParam()
            }
        }
        
    }
    
    @objc func selectmaskdelete(_ gestureRecognizer: UILongPressGestureRecognizer) {
        let p: CGPoint = gestureRecognizer.location(in: maskTableView)
        let indexPath: IndexPath? = maskTableView.indexPathForRow(at: p)
        selectedcell = (indexPath?.row)!
        print("selection mask Delete TEST \(String(describing: indexPath?.row)) ")
        //    [self performSegueWithIdentifier:@"MaskEdit" sender:nil];
        
        let alert = UIAlertController(title: "Edit Mask", message: "Do you want to Edit this Mask or Delete this Mask?", preferredStyle: .alert)
        let edit = UIAlertAction(title: "Edit Mask", style: .default, handler: {(_ action: UIAlertAction) -> Void in
            self.performSegue(withIdentifier: "MaskEdit", sender: nil)
            self.maskTableView.reloadData()
            alert.dismiss(animated: true) {() -> Void in }
        })
        let delete = UIAlertAction(title: "Delete Mask", style: .default, handler: {(_ action: UIAlertAction) -> Void in
            if self.selectedcell < self.deletearray.count {
                if self.selectedcell == self.deletearray.count - 1 {
                    
                }
                else {
                    var i = self.selectedcell
                    while i < self.deletearray.count - 1 {
                        let changeused: EASelectMaskParam? = self.deletearray[i + 1] as? EASelectMaskParam
                        //                                         changeused.used = [appDelegate.mReader usedSelectionMask: i+1];
                        self.deletearray[i] = changeused ?? EASelectMaskParam()
                        i = i+1
                    }
                    
                }
                self.deletearray.remove(at: self.deletearray.count - 1)
            }
            self.maskTableView.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(edit)
        alert.addAction(delete)
        alert.addAction(cancel)
        present(alert, animated: true) {() -> Void in }
    }
    func initLoadMask() {
        var param:EASelectMaskParam
        var _:Int
     
        for  i in MIN_SELECTION_MASK..<MAX_SELECTION_MASK {
            param = (appDelegate.mReader?.getSelectionMask(Int32(i)))!
            if !(param.mask == "") && (param != nil) {
                maskData.append(param)
                checklist.append(param)
                deletearray.append(param)
                print("DEBUG. maskData addObject [\(i), \(param)]")
            }
        }
        for i in MIN_SELECTION_MASK..<MAX_SELECTION_MASK {
            if (appDelegate.mReader?.usedSelectionMask(i))! {
                let replaceParam: EASelectMaskParam? = maskData[Int(i)] as? EASelectMaskParam
                print("DEBUG. usedSelectionMask [\(i), \(String(describing: replaceParam))]")
                replaceParam?.used = true
                checklist[Int(i)] = replaceParam ?? EASelectMaskParam()
                deletearray[Int(i)] = replaceParam ?? EASelectMaskParam()
                maskData[Int(i)] = replaceParam ?? EASelectMaskParam()
            }
        }
        DispatchQueue.main.async(execute: {() -> Void in
            self.maskTableView.reloadData()
            self.HUD.hide(true)
            self.HUD.removeFromSuperview()
        })
    }

    @IBAction func cancelBtnTapped(_ sender: UIButton) {
        navigationController?.popViewController(animated: true)
    }
    
    @IBAction func saveBtnTapped(_ sender: UIButton) {
        var param: EASelectMaskParam?
        checkarray.removeAll()
        
        self.HUD = MBProgressHUD(view: self.navigationController?.view)
        self.HUD.labelText = "Saving..."
        self.HUD.show(true)
        self.navigationController?.view.addSubview(self.HUD)
        //        })
        DispatchQueue.global(qos: .default).async(execute: {() -> Void in
            
            for i in MIN_SELECTION_MASK..<MAX_SELECTION_MASK {
                if i < self.deletearray.count {
                    var arrayParam: EASelectMaskParam?
                    arrayParam = self.deletearray[Int(i)] as? EASelectMaskParam
                    if arrayParam?.used == true {
                        self.checkarray.append(self.deletearray[Int(i)])
                        param = self.deletearray[Int(i)] as? EASelectMaskParam
                        self.appDelegate.mReader?.setSelectionMask(i, with: param)
                        self.appDelegate.mReader?.setMaskUsed(i, used: true)
                    }
                    else {
                        param = self.deletearray[Int(i)] as? EASelectMaskParam
                        self.appDelegate.mReader?.setSelectionMask(i, with: param)
                        self.appDelegate.mReader?.setMaskUsed(i, used: false)
                        self.appDelegate.mReader?.removeSelectionMask(i)
                    }
                    print("saveBtnTapped Selection Mask [\(i), \(String(describing: arrayParam) )]")
                }
                else {
                    let deletearrayParam = EASelectMaskParam()
                    deletearrayParam.mask = ""
                    deletearrayParam.length = 0
                    self.appDelegate.mReader?.setSelectionMask(i, with: deletearrayParam)
                    self.appDelegate.mReader?.setMaskUsed(i, used: false)
                    self.appDelegate.mReader?.removeSelectionMask(i)
                }
            }
            
            let selectFlagValue = Int(Float(((self.appDelegate.mReader?.useSelectionMask)?.rawValue)!))
            if(self.checkarray.count > 0){
                if (selectFlagValue == 0){
                    self.appDelegate.mReader?.useSelectionMask = (SelectFlag(rawValue: SelectFlag.RawValue(selectFlagValue + 1)))
                } else {
                    self.appDelegate.mReader?.useSelectionMask = (SelectFlag(rawValue: SelectFlag.RawValue(selectFlagValue)))
                }
            } else {
                self.appDelegate.mReader?.useSelectionMask = (SelectFlag(rawValue: SelectFlag.RawValue(0)))
            }
            self.navigationController?.popViewController(animated: true)
            
            DispatchQueue.main.async(execute: {() -> Void in
                self.HUD.hide(true)
                self.HUD.removeFromSuperview()
            })
        })
    }
    @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.HUD.hide(true)
            self.HUD.removeFromSuperview()
            self.appDelegate.mPeripheral = nil
            self.appDelegate.connectflag = false
            self.performSegue(withIdentifier: "ReadMemory", sender: nil)
        })
    }
}
