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

import UIKit

class MaterialsOptions{
    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 ChooseMaterialTableViewController: UITableViewController {

    var Materials = [MaterialsOptions]()
    
    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.loadMaterials()
        
        tableView.tableFooterView = UIView()
    }

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

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "ChooseMaterialTableViewCell"
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? ChooseMaterialTableViewCell
            else {
                fatalError("The dequeued cell is not an instance of ChooseMaterialTableViewCell.")
        }
        
        // Fetches the appropriate meal for the data source layout.
        let MaterialsOption = Materials[indexPath.row]
        
        cell.nameLabel.text = MaterialsOption.name
        cell.nameLabel.sizeToFit()
        let selectedSetup = UserDefaults.standard.string(forKey: "Reference_material")
        if(selectedSetup != nil){
            if(selectedSetup == cell.nameLabel.text){
                cell.accessoryType = UITableViewCellAccessoryType.checkmark
            }
        }else if(cell.nameLabel.text == "TS5"){
            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(Materials[indexPath.row].name == "TS5"){
            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: "Materials_options") != nil){
                var currentOptions = UserDefaults.standard.object(forKey: "Materials_options") as! [String : String]
                if let result  = currentOptions.first(where: {(key, _) in key.range(of: Materials[indexPath.row].name, options: .caseInsensitive) != nil}) {
                    currentOptions.removeValue(forKey: result.key)
                }
                
                UserDefaults.standard.removeObject(forKey: "Materials_options")
                UserDefaults.standard.set(currentOptions, forKey: "Materials_options")
                UserDefaults.standard.synchronize()
                
            }
            
            let selectedSetup = UserDefaults.standard.string(forKey: "Reference_material")
            if(selectedSetup == Materials[indexPath.row].name){
                UserDefaults.standard.set("TS5", forKey: "Reference_material")
            }
            
            Materials.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 loadMaterials() {
        
        if(UserDefaults.standard.object(forKey: "Materials_options") != nil){
            let currentOptions = UserDefaults.standard.object(forKey: "Materials_options") as! [String : String]
            
            for (key, _) in currentOptions{
                guard let Materials1 = MaterialsOptions(name: key)
                    else {
                        fatalError("Unable to instantiate settings1")
                }
                Materials += [Materials1]
            }
        }else{
            guard let Materials1 = MaterialsOptions(name: "TS5")
                else {
                    fatalError("Unable to instantiate settings1")
            }
            Materials += [Materials1]
        }
    }

    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(Materials[indexPath.row].name , forKey: "Reference_material")
    }
    
}
