//
//  OpticalSettingsTableViewController.swift
//  NeoSpectraMicroSwift
//
//  Created by Si-Ware on 11/12/17.
//  Copyright © 2017 siware. All rights reserved.
//

import UIKit

class OpticalSettingsOptions{
    var name : String
    init?(name: String) {
        
        // Initialization should fail if there is no name or if the rating is negative.
        if name.isEmpty {
            return nil
        }
        
        // Initialize stored properties.
        self.name = name
        
    }
}

class OpticalSettingsTableViewController: UITableViewController {

    var OpticalSettings = [OpticalSettingsOptions]()
    
    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
        self.loadOpticalSettings()
        
        tableView.tableFooterView = UIView()
        /*let tableViewFooter = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 50))
        tableViewFooter.backgroundColor = UIColor.clear
        let version = UILabel(frame: CGRect(x: 8, y: 15, width: tableView.frame.width, height: 50))
        version.font = version.font.withSize(14)
        version.text = "Version 1.x"
        version.textColor = UIColor.lightGray
        version.textAlignment = .left;
        
        tableViewFooter.addSubview(version)
        
        tableView.tableFooterView  = tableViewFooter*/
    }

    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 OpticalSettings.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "OpticalSettingsTableViewCell"
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? OpticalSettingsTableViewCell
            else {
                fatalError("The dequeued cell is not an instance of OpticalSettingsTableViewCell.")
        }
        
        // Fetches the appropriate meal for the data source layout.
        let OpticalSettingsOption = OpticalSettings[indexPath.row]
        
        cell.nameLabel.text = OpticalSettingsOption.name
        cell.nameLabel.sizeToFit()
        let selectedSetup = UserDefaults.standard.string(forKey: "Optical_gain_settings_title")
        if(selectedSetup != nil){
            if(selectedSetup == cell.nameLabel.text){
                cell.accessoryType = UITableViewCellAccessoryType.checkmark
            }
        }else if(cell.nameLabel.text == "Default"){
            cell.accessoryType = UITableViewCellAccessoryType.checkmark
        }
        
        return cell
    }
    

    
    // 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.
        
        if(OpticalSettings[indexPath.row].name == "Default"){
            return false
        }else{
            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
            if(UserDefaults.standard.object(forKey: "Optical_gain_settings_options") != nil){
                let kitID = Constants.SelectedDeviceName.components(separatedBy: "_")[1]
                var currentOptions = UserDefaults.standard.object(forKey: "Optical_gain_settings_options") as! [String : String]
                if let result  = currentOptions.first(where: {(key, _) in key.range(of: OpticalSettings[indexPath.row].name + "_" + kitID, options: .caseInsensitive) != nil}) {
                    currentOptions.removeValue(forKey: result.key)
                }
                
                UserDefaults.standard.removeObject(forKey: "Optical_gain_settings_options")
                UserDefaults.standard.set(currentOptions, forKey: "Optical_gain_settings_options")
                UserDefaults.standard.synchronize()
                
            }
            
            let selectedSetup = UserDefaults.standard.string(forKey: "Optical_gain_settings_title")
            if(selectedSetup == OpticalSettings[indexPath.row].name){
               UserDefaults.standard.set("Default", forKey: "Optical_gain_settings_title")
            }
            
            OpticalSettings.remove(at: indexPath.row)
            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.
    }
    */
    
    private func loadOpticalSettings() {
        
        if(UserDefaults.standard.object(forKey: "Optical_gain_settings_options") != nil){
            if(Constants.SelectedDeviceName == ""){
                guard let OpticalSettings1 = OpticalSettingsOptions(name: "Default")
                    else {
                        fatalError("Unable to instantiate settings1")
                }
                OpticalSettings += [OpticalSettings1]
            }else{
                let currentOptions = UserDefaults.standard.object(forKey: "Optical_gain_settings_options") as! [String : String]
                
                for (key, _) in currentOptions{
                    let kitID = Constants.SelectedDeviceName.components(separatedBy: "_")[1]
                    if(key.contains(kitID)){
                        let setupName = key.components(separatedBy: "_")[0]
                        guard let OpticalSettings1 = OpticalSettingsOptions(name: setupName)
                            else {
                                fatalError("Unable to instantiate settings1")
                        }
                        OpticalSettings += [OpticalSettings1]
                    }else if(key == "Default"){
                        guard let OpticalSettings1 = OpticalSettingsOptions(name: key)
                            else {
                                fatalError("Unable to instantiate settings1")
                        }
                        OpticalSettings += [OpticalSettings1]
                    }
                }
            }
        }else{
            guard let OpticalSettings1 = OpticalSettingsOptions(name: "Default")
                else {
                    fatalError("Unable to instantiate settings1")
            }
            OpticalSettings += [OpticalSettings1]
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        
        //let selectedSetup = UserDefaults.standard.string(forKey: "Optical_gain_settings_title")
        //let index = OpticalSettings.index(where: { (item) -> Bool in
        //    item.name == selectedSetup
        //})
        for row in 0..<tableView.numberOfRows(inSection: indexPath.section) {
            if let cell = tableView.cellForRow(at: IndexPath(row: row, section: indexPath.section)) {
                cell.accessoryType = row == indexPath.row ? .checkmark : .none
            }
        }
        let cell = tableView.cellForRow(at: IndexPath(row: indexPath.row, section: indexPath.section))
        cell?.accessoryType = UITableViewCellAccessoryType.checkmark
        tableView.deselectRow(at: indexPath, animated: true)
        
        UserDefaults.standard.set(OpticalSettings[indexPath.row].name , forKey: "Optical_gain_settings_title")
    }
    
}
