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

import UIKit

class SettingTableViewController: UITableViewController, EAReaderDelegate {

    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    var rfidmenuItems: NSArray?
    var countryarray: NSArray?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        
        if ( appDelegate.devicename!.range(of: "AT388") != nil) || ( appDelegate.devicename?.range(of: "ATS100") != nil || appDelegate.devicename?.range(of: "ATS200") != 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 {
            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"]

        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        appDelegate.mReader?.setDelegate(self)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return rfidmenuItems!.count
    }

  
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
        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(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
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if(indexPath.row == 2){
            self.inventoryTimeSetting()
        } 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
            }
        }
        tableView.reloadData()
    }
    func inventoryTimeSetting() {
        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.tableView.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(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.tableView.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 }
        })
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return 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.
    }
    */

}
