import { Component, OnInit, ViewChild } from '@angular/core';
import { PickerController } from '@ionic/angular';
import { ControllerService } from '../services/controller.service';
import { UIService } from '../services/ui.service';

@Component({
  selector: 'app-airconditioning',
  templateUrl: './airconditioning.page.html',
  styleUrls: ['./airconditioning.page.scss'],
})
export class AirconditioningPage implements OnInit {

  echoDevices: Object;
  echoClimateData: Object;

  mainAirConditioner = this.controllerService.echoDeviceUUIDS['Main Air Conditioner'];
  mainAirConditionerStatus: Boolean;

  constructor(public pickerController: PickerController, public controllerService: ControllerService, public uiService: UIService) {}

  ngOnInit() {
    this.controllerService.echoDevices.subscribe(data => { this.echoDevices = data});
    this.controllerService.echoClimateLog.subscribe(data => { this.echoClimateData = data});
  }

  ionViewWillEnter() {
    this.controllerService.updateAllData();
    setInterval(() => this.updateDeviceStatus(), 1000);
    this.updateDeviceStatus();
  }

  updateDeviceStatus = async () => {
    if(this.echoDevices.hasOwnProperty(this.mainAirConditioner)) {
      if((this.echoDevices[this.mainAirConditioner]['status'] == "on") || (this.echoDevices[this.mainAirConditioner]['status'] == "busy")) {
        this.mainAirConditionerStatus = true;
      } else {
        this.mainAirConditionerStatus = false;
      }
    }
  }

  getCurrentSpeed = () => {
    if(this.echoDevices.hasOwnProperty(this.mainAirConditioner)) {
      let speed = this.echoDevices[this.mainAirConditioner]['fan_speed'];
      return speed.charAt(0).toUpperCase() + speed.substring(1);
    } else {
      return '-';
    }
  }

  getCurrentMode = () => {
    if(this.echoDevices.hasOwnProperty(this.mainAirConditioner)) {
      let mode = this.echoDevices[this.mainAirConditioner]['mode'];
      return mode.charAt(0).toUpperCase() + mode.substring(1);
    } else {
      return '-';
    }
  }

  getCurrentTemperature = () => {
    if(this.echoClimateData.hasOwnProperty('temperature')) {
      return this.echoClimateData['temperature'].toString().replace('.', ',');
    } else {
      return "...";
    }
  }

  getCurrentHumidity = () => {
    if(this.echoClimateData.hasOwnProperty('humidity')) {
      return this.echoClimateData['humidity'].toString().replace('.', ',');
    } else {
      return "...";
    }
  }

  getCurrentTargetTemperature = () => {
    if(this.echoDevices.hasOwnProperty(this.mainAirConditioner)) {
      return this.echoDevices[this.mainAirConditioner]['target_temperature'].toString();
    } else {
      return '-';
    }
  }

  setMainAirConditionerSpeed = async () => {
    let new_speed;

    if (this.echoDevices[this.mainAirConditioner]['mode'] == "low") {
      new_speed = "high"
    }

    if (this.echoDevices[this.mainAirConditioner]['mode'] == "high") {
      new_speed = "low"
    }

    let response = await this.controllerService.handleDeviceAction(this.mainAirConditioner, "set_fan_speed", new_speed);
    await this.uiService.presentToast(response['message']);
  }

  switchMainAirConditioner = async () => {
    let action;

    if(this.mainAirConditionerStatus == false){
      action = "on";
    } else {
      action = "off";
    }

    let response = await this.controllerService.handleDeviceAction(this.mainAirConditioner, action);
    await this.uiService.presentToast(response['message']);
  }


  openModePicker = async () => {

    const picker = await this.pickerController.create({
      columns: [
        {
          name: "Mode",
          options: [
            {
              text: "Cooling",
              value: "cooling"
            },
            {
              text: "Dehumidifying",
              value: "dehumidifying"
            },
            {
              text: "Blowing",
              value: "blowing"
            }
          ]
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Set mode',
          handler: (selectedMode) => {
            console.log(selectedMode)
            let mode = selectedMode['Mode']['value'];
            
            this.controllerService.handleDeviceAction(this.mainAirConditioner, 'set_mode', mode)
            .then((response) => {
              this.uiService.presentToast(response['message']);
            })
          }
        }
      ]
    });

    await picker.present();
  }

  openTargetTemperaturePicker = async () => {

    const picker = await this.pickerController.create({
      columns: [
        {
          name: "Temperature",
          options: this.getPickerTemperatures()
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Set Target Temperature',
          handler: (selectedTemperature) => {
            console.log(selectedTemperature);
            let temperature = selectedTemperature['Temperature']['value'];
            
            this.controllerService.handleDeviceAction(this.mainAirConditioner, 'set_temperature', temperature)
            .then((response) => {
              this.uiService.presentToast(response['message']);
            })

          }
        }
      ]
    });

    await picker.present();
  }

  getPickerTemperatures = () =>  {
    let temps = [];

    for (let index = 16; index < 31; index++) {
      temps.push({
        text: index,
        value: index
      }) 
    }

    return temps;
  }



}