//
//  AddTimeEventViewController.swift
//  Home
//
//  Created by Richard Kuckovsky on 10.5.17.
//  Copyright © 2017 Richard Kuckovsky. All rights reserved.
//

import UIKit

class AddTimeEventViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var txt_name: UITextField!
    @IBOutlet weak var pckr_time: UIDatePicker!
    @IBOutlet weak var pckr_output: UIPickerView!
    @IBOutlet weak var lbl_days: UILabel!
    
    @IBOutlet weak var output_switch: UISwitch!
    @IBOutlet weak var output_slider: UISlider!
    @IBOutlet weak var output_lbl_temp: UILabel!
    @IBOutlet weak var output_img_temp: UIImageView!
    
    @IBOutlet weak var btn_done: UIBarButtonItem!
    
    var room_id = 0
    var room_index = 0
    var event_index = 0
    
    var selected_days = [Int]()
    var outputs = [outputsType]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
        
        selected_days = [1, 1, 1, 1, 1, 1, 1]

        pckr_output.delegate = self
        pckr_output.dataSource = self
        
        output_img_temp.tintColor = UIColor(red: 85/255, green: 85/255, blue: 85/255, alpha: 1)
        
        if(outputs[0].type == "switch") {
            output_switch.isHidden = false
        } else if(outputs[0].type == "slider") {
            output_slider.isHidden = false
            output_slider.maximumValue = Float(outputs[0].max_value)
            output_slider.minimumValue = Float(outputs[0].min_value)
        } else if(outputs[0].type == "termostat") {
            output_lbl_temp.isHidden = false
            output_img_temp.isHidden = false
        }
        
    }
    
    func dismissKeyboard() {
        view.endEditing(true)
        // do aditional stuff
    }
    
    @IBAction func cancel_btn(_ sender: Any) {
        self.dismiss(animated: true)
    }
    
    @IBAction func name_txt(_ sender: Any) {
        var days = 0
        for day in self.selected_days {
            days += day
        }
        if((days > 0) && (self.outputs.count > 0) && (self.txt_name.text != "")) {
            self.btn_done.isEnabled = true
        } else {
            self.btn_done.isEnabled = false
        }
    }
    @IBAction func done_btn(_ sender: Any) {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        let selectedDate = dateFormatter.string(from: self.pckr_time.date)
        var days_array = [Int]()
        
        var i = 1;
        for day in selected_days {
            if(day == 1) {
                days_array.append(i)
            }
            i += 1
        }
        
        let separator = ","
        let days = days_array.flatMap{ String($0) }.joined(separator: separator)

        var value = 0
        var temp = 0.0
        
        if(outputs[self.pckr_output.selectedRow(inComponent: 0)].type == "switch") {
            if(output_switch.isOn) {
                value = outputs[self.pckr_output.selectedRow(inComponent: 0)].max_value
            } else {
                value = outputs[self.pckr_output.selectedRow(inComponent: 0)].min_value
            }
        } else if(outputs[self.pckr_output.selectedRow(inComponent: 0)].type == "slider") {
            value = Int(output_slider.value)
        } else if(outputs[self.pckr_output.selectedRow(inComponent: 0)].type == "button") {
            value = outputs[self.pckr_output.selectedRow(inComponent: 0)].max_value
        } else if(outputs[self.pckr_output.selectedRow(inComponent: 0)].type == "termostat") {
            value = 0
            temp = 0.0
        }
        
        SocketIOManager.sharedInstance.addEvent(room: self.room_id, name: self.txt_name.text!, type: "time", sensor: 0, start: selectedDate, stop: "", timeout: 0, days: days, event_on: 0, output: outputs[self.pckr_output.selectedRow(inComponent: 0)].id, value: value, temp: Float(temp)) { (status, id) in
            
            var new_event = eventsType()
            
            new_event.id = id
            new_event.room_index = self.room_index
            new_event.event_index = self.event_index
            new_event.name = self.txt_name.text!
            new_event.type = "time"
            new_event.start = selectedDate
            new_event.days = days
            new_event.output = self.outputs[self.pckr_output.selectedRow(inComponent: 0)].id
            new_event.value = value
            new_event.active = 1
            
            rooms[self.room_index].events.append(new_event)
            

            
            if let presenter = self.presentingViewController as? UITabBarController {
                if let roomsController = presenter.viewControllers?[1] as? UINavigationController {
                    if let room = roomsController.viewControllers[1] as? RoomController {
                        room.events.append(new_event)
                    }
                }
            } else if let roomsController = self.presentingViewController as? UINavigationController {
                if let room = roomsController.viewControllers[1] as? RoomController {
                    room.events.append(new_event)                }
            } else if let room = self.presentingViewController as? RoomController {
                room.events.append(new_event)
            }
            
            self.dismiss(animated: true)
        }
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        var days = 0
        var days_string = ""
        var i = 0
        for day in self.selected_days {
            days += day
            if(day == 1) {
                if(i == 0) { days_string += " Po" }
                if(i == 1) { days_string += " Ut" }
                if(i == 2) { days_string += " St" }
                if(i == 3) { days_string += " Št" }
                if(i == 4) { days_string += " Pi" }
                if(i == 5) { days_string += " So" }
                if(i == 6) { days_string += " Ne" }
            }
            i += 1
        }
        
        if(days == 7) {
            lbl_days.text = "Každý deň"
        } else {
            lbl_days.text = days_string
        }
        
        if((days > 0) && (outputs.count > 0) && (txt_name.text != "")) {
            btn_done.isEnabled = true
        } else {
            btn_done.isEnabled = false
        }

        
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    // The number of rows of data
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return outputs.count
    }
    
    // The data to return for the row and component (column) that's being passed in
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        
        return  outputs[row].name
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        output_lbl_temp.isHidden = true
        output_img_temp.isHidden = true
        output_slider.isHidden = true
        output_switch.isHidden = true
        
        if(outputs[row].type == "switch") {
            output_switch.isHidden = false
        } else if(outputs[row].type == "slider") {
            output_slider.isHidden = false
            output_slider.maximumValue = Float(outputs[row].max_value)
            output_slider.minimumValue = Float(outputs[row].min_value)
        } else if(outputs[row].type == "termostat") {
            output_lbl_temp.isHidden = false
            output_img_temp.isHidden = false
        }
        
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if((indexPath.section == 2) && (indexPath.row == 0)) {
            if(outputs[self.pckr_output.selectedRow(inComponent: 0)].type == "termostat") {
                performSegue(withIdentifier: "termostat", sender: self)
            }
        }
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

   
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "show_days") {
            let destination = segue.destination as? PickDaysViewController
            destination?.selected_days = self.selected_days
            
        } else if(segue.identifier == "termostat") {
            if let DestinationController = segue.destination as? TermostatViewController {
                
                DestinationController.output = outputs[self.pckr_output.selectedRow(inComponent: 0)]
                
                DestinationController.origin = "set_time_event"
            }
        }
    }


}

class PickDaysViewController: UITableViewController {
    
    var selected_days = [Int]()
    
    @IBOutlet weak var cell_pon: UITableViewCell!
    @IBOutlet weak var cell_uto: UITableViewCell!
    @IBOutlet weak var cell_str: UITableViewCell!
    @IBOutlet weak var cell_stv: UITableViewCell!
    @IBOutlet weak var cell_pia: UITableViewCell!
    @IBOutlet weak var cell_sob: UITableViewCell!
    @IBOutlet weak var cell_ned: UITableViewCell!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {

            if(selected_days[0] == 1) {
                cell_pon.accessoryType = UITableViewCellAccessoryType.checkmark
            } else {
                cell_pon.accessoryType = UITableViewCellAccessoryType.none
            }

            if(selected_days[1] == 1) {
                cell_uto.accessoryType = UITableViewCellAccessoryType.checkmark
            } else {
                cell_uto.accessoryType = UITableViewCellAccessoryType.none
            }

            if(selected_days[2] == 1) {
                cell_str.accessoryType = UITableViewCellAccessoryType.checkmark
            } else {
                cell_str.accessoryType = UITableViewCellAccessoryType.none
            }

            if(selected_days[3] == 1) {
                cell_stv.accessoryType = UITableViewCellAccessoryType.checkmark
            } else {
                cell_stv.accessoryType = UITableViewCellAccessoryType.none
            }

            if(selected_days[4] == 1) {
                cell_pia.accessoryType = UITableViewCellAccessoryType.checkmark
            } else {
                cell_pia.accessoryType = UITableViewCellAccessoryType.none
            }

            if(selected_days[5] == 1) {
                cell_sob.accessoryType = UITableViewCellAccessoryType.checkmark
            } else {
                cell_sob.accessoryType = UITableViewCellAccessoryType.none
            }

            if(selected_days[6] == 1) {
                cell_ned.accessoryType = UITableViewCellAccessoryType.checkmark
            } else {
                cell_ned.accessoryType = UITableViewCellAccessoryType.none
            }
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if(indexPath.row == 0) {
            if(selected_days[0] == 1) {
                cell_pon.accessoryType = UITableViewCellAccessoryType.none
                selected_days[0] = 0
            } else {
                cell_pon.accessoryType = UITableViewCellAccessoryType.checkmark
                selected_days[0] = 1
            }
        } else if(indexPath.row == 1) {
            if(selected_days[1] == 1) {
                cell_uto.accessoryType = UITableViewCellAccessoryType.none
                selected_days[1] = 0
            } else {
                cell_uto.accessoryType = UITableViewCellAccessoryType.checkmark
                selected_days[1] = 1
            }
        } else if(indexPath.row == 2) {
            if(selected_days[2] == 1) {
                cell_str.accessoryType = UITableViewCellAccessoryType.none
                selected_days[2] = 0
            } else {
                cell_str.accessoryType = UITableViewCellAccessoryType.checkmark
                selected_days[2] = 1
            }
        } else if(indexPath.row == 3) {
            if(selected_days[3] == 1) {
                cell_stv.accessoryType = UITableViewCellAccessoryType.none
                selected_days[3] = 0
            } else {
                cell_stv.accessoryType = UITableViewCellAccessoryType.checkmark
                selected_days[3] = 1
            }
        } else if(indexPath.row == 4) {
            if(selected_days[4] == 1) {
                cell_pia.accessoryType = UITableViewCellAccessoryType.none
                selected_days[4] = 0
            } else {
                cell_pia.accessoryType = UITableViewCellAccessoryType.checkmark
                selected_days[4] = 1
            }
        } else if(indexPath.row == 5) {
            if(selected_days[5] == 1) {
                cell_sob.accessoryType = UITableViewCellAccessoryType.none
                selected_days[5] = 0
            } else {
                cell_sob.accessoryType = UITableViewCellAccessoryType.checkmark
                selected_days[5] = 1
            }
        } else if(indexPath.row == 6) {
            if(selected_days[6] == 1) {
                cell_ned.accessoryType = UITableViewCellAccessoryType.none
                selected_days[6] = 0
            } else {
                cell_ned.accessoryType = UITableViewCellAccessoryType.checkmark
                selected_days[6] = 1
            }
        }
        
    }
    
    override func willMove(toParentViewController parent: UIViewController?) {
        if(parent == nil) {
            if let destination = self.navigationController?.viewControllers[0] as? AddTimeEventViewController {
                destination.selected_days = self.selected_days
            }
            if let destination = self.navigationController?.viewControllers[0] as? AddSensorEventViewController {
                destination.selected_days = self.selected_days
            }
        }
        
    }
    
    /*
     // 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.
     }
     */
    
}
