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

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

  currentTimeHour: Number;
  currentTimeMinute: Number;
  currentDateDay: Number;
  currentMonth: String;
  currentYear: Number;

  echoConnectionError: Boolean;
  echoDevices: Object;
  echoClimateData: Object;
  echoLightData: Object;

  mainLight = this.controllerService.echoDeviceUUIDS['Main Light'];
  mainAirConditioner = this.controllerService.echoDeviceUUIDS['Main Air Conditioner'];

  mainLightToggle: Boolean;
  mainAirConditionerToggle: Boolean;

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

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

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

  updateTime = () => {
    let monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
    ];

    let now = new Date();
    this.currentTimeHour = this.pad(now.getHours(), 2, 0);
    this.currentTimeMinute = this.pad(now.getMinutes(), 2, 0);
    this.currentDateDay = now.getDate();
    this.currentMonth = monthNames[now.getMonth()];
    this.currentYear = now.getFullYear();
  }

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

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

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

  getLight = () => {
    if(this.echoLightData.hasOwnProperty('light_amount')) {
      let currentValue = this.echoLightData['light_amount'];
      let maxLight = 600;
      let onePercent = (100 / maxLight);
      let currenPercentage = (currentValue * onePercent).toFixed(1).toString().replace('.', ',');
      return currenPercentage;
    } else {
      return "...";
    }
  }

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

  updateDeviceStatus = () => {
    if(this.echoDevices.hasOwnProperty(this.mainLight)) {
      if(this.echoDevices[this.mainLight]['status'] == "on") {
        this.mainLightToggle = true;
      } else {
        this.mainLightToggle = false;
      }
    }

    
    if(this.echoDevices.hasOwnProperty(this.mainAirConditioner)) {
      if(this.echoDevices[this.mainAirConditioner]['status'] == "on") {
        this.mainAirConditionerToggle = true;
      } else {
        this.mainAirConditionerToggle = false;
      }
    }
  }

  switchMainLight = async () => {
    let action;

    if(this.mainLightToggle == true){
      action = "on";
    } else {
      action = "off";
    }

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

  switchMainAirConditioner = async () => {
    let action;

    if(this.mainAirConditionerToggle == true){
      action = "on";
    } else {
      action = "off";
    }

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

}
