//
//  AddSensorEventViewController.swift
//  Home
//
//  Created by Richard Kuckovsky on 11.5.17.
//  Copyright © 2017 Richard Kuckovsky. All rights reserved.
//

import UIKit

class AddSensorEventViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    
    @IBOutlet weak var txt_name: UITextField!
    @IBOutlet weak var pckr_time_from: UIDatePicker!
    @IBOutlet weak var pckr_time_to: UIDatePicker!
    @IBOutlet weak var pckr_event_duration: UIDatePicker!
    @IBOutlet weak var pckr_sensors: UIPickerView!
    @IBOutlet weak var pckr_outputs: UIPickerView!
    @IBOutlet weak var lbl_days: UILabel!
    
    @IBOutlet weak var output_switch: UISwitch!
    @IBOutlet weak var output_slider: UISlider!
    @IBOutlet weak var output_img_temp: UIImageView!
    @IBOutlet weak var output_lbl_temp: UILabel!
    
    
    var outputs = [outputsType]()
    var sensors = [sensorsType]()
    
    var room_id = 0
    var room_index = 0
    var event_index = 0
    
    
    var selected_days = [Int]()

    override func viewDidLoad() {
        super.viewDidLoad()
        
         self.hideKeyboardOnTap(#selector(self.dismissKeyboard))
        
        selected_days = [1, 1, 1, 1, 1, 1, 1]

        
        pckr_outputs.delegate = self
        pckr_outputs.dataSource = self
        
        pckr_sensors.delegate = self
        pckr_sensors.dataSource = self
        
        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 done_btn(_ sender: Any) {
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        let start = dateFormatter.string(from: self.pckr_time_from.date)
        let stop = dateFormatter.string(from: self.pckr_time_to.date)
        dateFormatter.dateFormat = "HH"
        let timeout_h : Int = Int(dateFormatter.string(from: self.pckr_event_duration.date))!
        dateFormatter.dateFormat = "mm"
        let timeout_m : Int = Int(dateFormatter.string(from: self.pckr_event_duration.date))!
        
        let timeout = timeout_h*60 + timeout_m
        
        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_outputs.selectedRow(inComponent: 0)].type == "switch") {
            print("tu sa to dojebava zase....")
            if(output_switch.isOn) {
                value = outputs[self.pckr_outputs.selectedRow(inComponent: 0)].max_value
            } else {
                value = outputs[self.pckr_outputs.selectedRow(inComponent: 0)].min_value
            }
        } else if(outputs[self.pckr_outputs.selectedRow(inComponent: 0)].type == "slider") {
            value = Int(output_slider.value)
        } else if(outputs[self.pckr_outputs.selectedRow(inComponent: 0)].type == "button") {
            value = outputs[self.pckr_outputs.selectedRow(inComponent: 0)].max_value
        } else if(outputs[self.pckr_outputs.selectedRow(inComponent: 0)].type == "termostat") {
            value = 0
            temp = 0.0
        }
        

        SocketIOManager.sharedInstance.addEvent(room: self.room_id, name: self.txt_name.text!, type: "sensor", sensor: sensors[self.pckr_sensors.selectedRow(inComponent: 0)].id, start: start, stop: stop, timeout: timeout, days: days, event_on: 1, output: outputs[self.pckr_outputs.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 = "push"
            new_event.start = start
            new_event.stop = stop
            new_event.timeout = timeout
            new_event.days = days
            new_event.output = self.outputs[self.pckr_outputs.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 {
        
        if(pickerView == pckr_sensors) {
            return sensors.count
        } else if (pickerView == pckr_outputs) {
            return outputs.count
        }
        return 0
    }
    
    // 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? {
        
        if(pickerView == pckr_sensors) {
            return sensors[row].name
        } else if (pickerView == pckr_outputs) {
            return outputs[row].name
        }
        
        return  ""
    }
    
    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 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"
           // }
        }
    }

}
