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

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

  echoDevices: Object;

  mainSunBlinds = this.controllerService.echoDeviceUUIDS['Main Sun Blinds'];
  mainSunBlindsStatus: string;
  mainSunBlindsAuto: boolean;
  mainSunBlindsAutoTime: string;

  doingAction: boolean = false;

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

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

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

  updateDeviceStatus = () => {
    if(this.echoDevices.hasOwnProperty(this.mainSunBlinds)) {
      if(this.echoDevices[this.mainSunBlinds]['status'] == "preset") {
        this.mainSunBlindsStatus = this.echoDevices[this.mainSunBlinds]['presets'][this.echoDevices[this.mainSunBlinds]['current_preset']]['name'];
      }

      if(this.echoDevices[this.mainSunBlinds]['status'] == "custom") {
        this.mainSunBlindsStatus = "Custom";
      }

      if(this.echoDevices[this.mainSunBlinds]['automatic_open'] == true) {
        this.mainSunBlindsAuto = true;
        this.mainSunBlindsAutoTime = this.echoDevices[this.mainSunBlinds]['automatic_open_time'];
      } else {
        this.mainSunBlindsAuto = false;
        this.mainSunBlindsAutoTime = this.echoDevices[this.mainSunBlinds]['automatic_open_time'];
      }
    }
  }

  mainBlindsUp = async () => {
    if(this.doingAction == true) {
      let response = await this.controllerService.handleDeviceAction(this.mainSunBlinds, 'stop');
      this.uiService.presentToast(response['message']);
      this.doingAction = false;
    } else {
      this.doingAction = true;
      let response = await this.controllerService.handleDeviceAction(this.mainSunBlinds, 'up');
      if(response['status'] == "failed") {
        this.doingAction = false;
      }
      this.uiService.presentToast(response['message']);
    }
  }

  mainBlindsDown = async () => {
    if(this.doingAction == true) {
      let response = await this.controllerService.handleDeviceAction(this.mainSunBlinds, 'stop');
      this.uiService.presentToast(response['message']);
      this.doingAction = false;
    } else {
      this.doingAction = true;
      let response = await this.controllerService.handleDeviceAction(this.mainSunBlinds, 'down');
      if(response['status'] == "failed") {
        this.doingAction = false;
      }
      this.uiService.presentToast(response['message']);
    }
  }

  openPresetPicker = async () => {

    const picker = await this.pickerController.create({
      columns: [
        {
          name: "Preset",
          options: [
            {
              text: "Open",
              value: "open"
            },
            {
              text: "Open Ventilated",
              value: "open_ventilated"
            },
            {
              text: "Closed Ventilated",
              value: "closed_ventilated"
            },
            {
              text: "Closed",
              value: "closed"
            },
          ]
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Execute',
          handler: (selectedPreset) => {
            console.log(selectedPreset)
            let preset = selectedPreset['Preset']['value'];
            
            this.controllerService.handleDeviceAction(this.mainSunBlinds, 'preset', preset)
            .then((response) => {
              this.uiService.presentToast(response['message']);
            })
          }
        }
      ]
    });

    await picker.present();
  }

  openAutoTimerPicker = async () => {

    const picker = await this.pickerController.create({
      columns: [
        {
          name: "Hour",
          options: this.getPickerHours()
        },
        {
          name: "Minutes",
          options: this.getPickerMinutes()
        }
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Set Time',
          handler: (selectedTime) => {
            let timeData = selectedTime['Hour']['text'] + ":" + selectedTime['Minutes']['text']
            
            this.controllerService.handleDeviceAction(this.mainSunBlinds, 'set_automatic_time', timeData)
            .then((response) => {
              this.uiService.presentToast(response['message']);
            })

          }
        }
      ]
    });

    await picker.present();
  }

  pad = (n, width, z) => {
    z = z || '0';
    n = n + '';
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
  }

  getPickerHours = () =>  {
    let hours = [];

    hours.push({
      text: "--",
      value: "--"
    })

    for (let index = 0; index < 25; index++) {

      hours.push({
        text: this.pad(index, 2, 0),
        value: this.pad(index, 2, 0)
      })
      
    }

    return hours;
  }

  getPickerMinutes = () => {
    let minutes = [];

    minutes.push({
      text: "--",
      value: "--"
    })

    for (let index = 0; index < 61; index++) {

      minutes.push({
        text: this.pad(index, 2, 0),
        value: this.pad(index, 2, 0)
      })
      
    }

    return minutes;
  }

}
