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

import UIKit

class AddNewMaterialViewController: UIViewController {
    
    var Name = ""
    var Peaks = ["0", "0", "0", "0", "0"]
    
    @IBOutlet weak var textLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.textLabel.isHidden = true
        self.getname()
    }

    func getname(){
        let alertController = UIAlertController(title: "New Standard Calibrator", message:
            "Please enter the name of the new standard material.", preferredStyle: UIAlertControllerStyle.alert)
        
        alertController.addTextField { (configurationTextField) in
            //configure here your textfield
            configurationTextField.textColor = UIColor.black
            configurationTextField.keyboardType = UIKeyboardType.namePhonePad
        }
        
        alertController.addAction(UIAlertAction(title: "Proceed", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
            let textField = (alertController.textFields![0]) as UITextField
            self.isValidName(value: textField.text!)
        }))
        
        alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
            self.textLabel.isHidden = false
        }))
        
        DispatchQueue.main.async {
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    func isValidName(value : String){
        if(value == ""){
            let alertController = UIAlertController(title: "Error", message:
                "You haven’t placed a name for your material. Please make sure to type a name that you can refer to later.", preferredStyle: UIAlertControllerStyle.alert)
            
            alertController.addAction(UIAlertAction(title: "Return", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
                self.getname()
            }))
            
            DispatchQueue.main.async {
                self.present(alertController, animated: true, completion: nil)
            }
        }else if(value.caseInsensitiveCompare("TS5") == ComparisonResult.orderedSame){
            let alertController = UIAlertController(title: "Error", message:
                "TS5 material is the default material and can not be overwritten. Please choose another name.", preferredStyle: UIAlertControllerStyle.alert)
            
            alertController.addAction(UIAlertAction(title: "Return", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
                self.getname()
            }))
            
            DispatchQueue.main.async {
                self.present(alertController, animated: true, completion: nil)
            }
        }else if(self.nameAlreadyExists(setupName: value)){
            let alertController = UIAlertController(title: "Name Already Exists", message:
                "Another material has the same name. Do you want to overwrite it ?", preferredStyle: UIAlertControllerStyle.alert)
            
            
            alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
                self.Name = value
                self.getWavelengths()
            }))
            
            alertController.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
                self.getname()
            }))
            
            DispatchQueue.main.async {
                self.present(alertController, animated: true, completion: nil)
            }
        }else{
            
            self.Name = value
            self.getWavelengths()
        }
    }
    
    func nameAlreadyExists(setupName: String)-> Bool{
        if(UserDefaults.standard.object(forKey: "Materials_options") != nil){
            let currentSetupOptions = UserDefaults.standard.object(forKey: "Materials_options") as! [String : String]
            if currentSetupOptions.first(where: {(key, _) in key.range(of: setupName, options: .caseInsensitive) != nil}) != nil{
                return true
            }else{
                return false
            }
        }else{
            return false
        }
    }
    
    func getWavelengths(){
        let alert = UIAlertController(title: "Please list 5 characteristic peak wavelength values (in nm) of your standard material. If the material has less than 5 peaks, leave the value 0.", message: "", preferredStyle: UIAlertControllerStyle.alert)
        
        alert.addTextField { (configurationTextField) in
            //configure here your textfield
            configurationTextField.textColor = UIColor.black
            configurationTextField.keyboardType = UIKeyboardType.decimalPad
            configurationTextField.text = self.Peaks[0]
        }
        alert.addTextField { (configurationTextField) in
            //configure here your textfield
            configurationTextField.textColor = UIColor.black
            configurationTextField.keyboardType = UIKeyboardType.decimalPad
            configurationTextField.text = self.Peaks[1]
        }
        alert.addTextField { (configurationTextField) in
            //configure here your textfield
            configurationTextField.textColor = UIColor.black
            configurationTextField.keyboardType = UIKeyboardType.decimalPad
            configurationTextField.text = self.Peaks[2]
        }
        alert.addTextField { (configurationTextField) in
            //configure here your textfield
            configurationTextField.textColor = UIColor.black
            configurationTextField.keyboardType = UIKeyboardType.decimalPad
            configurationTextField.text = self.Peaks[3]
        }
        alert.addTextField { (configurationTextField) in
            //configure here your textfield
            configurationTextField.textColor = UIColor.black
            configurationTextField.keyboardType = UIKeyboardType.decimalPad
            configurationTextField.text = self.Peaks[4]
        }
        
        alert.addAction(UIAlertAction(title: "Set", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in
            let textField_1 = (alert.textFields![0]) as UITextField
            let textField_2 = (alert.textFields![1]) as UITextField
            let textField_3 = (alert.textFields![2]) as UITextField
            let textField_4 = (alert.textFields![3]) as UITextField
            let textField_5 = (alert.textFields![4]) as UITextField
            var flagCounter = 5
            if(self.isValidDoubleNumber(value: textField_1.text!)) {
                flagCounter = flagCounter - 1
                self.Peaks[0] = textField_1.text!
            }
            if(self.isValidDoubleNumber(value: textField_2.text!)) {
                flagCounter = flagCounter - 1
                self.Peaks[1] = textField_2.text!
            }
            if(self.isValidDoubleNumber(value: textField_3.text!)) {
                flagCounter = flagCounter - 1
                self.Peaks[2] = textField_3.text!
            }
            if(self.isValidDoubleNumber(value: textField_4.text!)) {
                flagCounter = flagCounter - 1
                self.Peaks[3] = textField_4.text!
            }
            if(self.isValidDoubleNumber(value: textField_5.text!)) {
                flagCounter = flagCounter - 1
                self.Peaks[4] = textField_5.text!
            }
            
            if(flagCounter > 0){
                self.promotPeaksError()
            }else{
                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: self.Name, options: .caseInsensitive) != nil}) {
                        currentOptions.removeValue(forKey: result.key)
                    }
                    currentOptions[self.Name] =  String(textField_1.text! + "_" + textField_2.text! + "_" + textField_3.text! + "_" + textField_4.text! + "_" + textField_5.text!)
                    
                    UserDefaults.standard.removeObject(forKey: "Materials_options")
                    UserDefaults.standard.set(currentOptions, forKey: "Materials_options")
                    UserDefaults.standard.synchronize()
                    
                }else{
                    let optionValue = String(textField_1.text! + "_" + textField_2.text! + "_" + textField_3.text! + "_" + textField_4.text! + "_" + textField_5.text!)
                    let newOptions = ["TS5" : "1446.65_1693.55_2248.2_0_0" , self.Name : optionValue]
                    UserDefaults.standard.set(newOptions, forKey: "Materials_options")
                    UserDefaults.standard.synchronize()
                }
                UserDefaults.standard.set(self.Name, forKey: "Reference_material")
                UserDefaults.standard.synchronize()
                
                self.textLabel.text = "New Standard Calibrator Added"
                self.textLabel.sizeToFit()
                self.textLabel.center = self.view.center
                self.textLabel.isHidden = false
            }
            
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
            self.textLabel.isHidden = false
        }))
        
        self.present(alert, animated: true, completion: {
        })
    }
    
    func isValidDoubleNumber(value: String)-> Bool
    {
        if(value == "") {return false}
        
        let instance = NumberFormatter()
        if((instance.number(from: value)?.doubleValue) == nil) {return false}
        
        let DoubleValue = instance.number(from: value)?.doubleValue
        if(DoubleValue != 0.0){
            if(DoubleValue! < 1350.0 || DoubleValue! > 2500.0){
                return false
            }
        }
        return true
    }
    
    func promotPeaksError(){
        let alertError = UIAlertController(title: "Error", message: "Please enter valid numbers between 1,350 – 2,500 nm.", preferredStyle: UIAlertControllerStyle.alert)
        alertError.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: { (UIAlertAction)in
            self.getWavelengths()
        }))
        
        self.present(alertError, animated: true, completion: {
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // 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.
    }
    */

}
