import { Component, OnInit, ViewChild,OnChanges } from '@angular/core';
import { Chart, ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label, BaseChartDirective } from 'ng2-charts';

import { MeasuresService } from 'src/app/services/measures.service';
import { PlantsService } from 'src/app/services/plants.service';
import { LogsService } from 'src/app/services/logs.service';

import { OrganizationsService } from '@app/services/organizations.service';

import { ActivatedRoute } from '@angular/router';
import { Observable, forkJoin } from 'rxjs';


import * as moment from 'moment';

import Swal from 'sweetalert2';
import { environment } from '@environments/environment';
import { HttpClient } from '@angular/common/http';
import { formatDate } from '@angular/common';

import {AngularMyDatePickerDirective,IAngularMyDpOptions, IMyDateModel} from 'angular-mydatepicker';

@Component({
  selector: 'app-assets',
  templateUrl: './assets.component.html',
  styleUrls: ['./assets.component.scss']
})

export class AssetsComponent implements OnInit {
  
  title = "Plantas";

  organizationId:string;
  listAssets:any;

  eProduced:any;
  error:boolean;
  errorMessage:string;
  errortest:any;
  chartjs:boolean;
  chart1: Chart;
  metersKeys:any;
  metersValues:any;
  view:string;
  energyDay:any;
  energyWeek:any;
  energyMonth:any;
  energyYear:any;

  //For daterange
  daysLabels:any = {su: 'Dom', mo: 'Lun', tu: 'Mar', we: 'Mie', th: 'Jue', fr: 'Vie', sa: 'Sab'};
  monthsLabels:any = { 1: 'Ene', 2: 'Feb', 3: 'Mar', 4: 'Abr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Ago', 9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dic' };
  todayBtnTxt:string = 'Hoy';
  
  myDpOptions: IAngularMyDpOptions = {
    dateRange: false,
    dateFormat: 'dd/mm/yyyy',
    dayLabels: this.daysLabels,
    monthLabels: this.monthsLabels,
    // other options are here...
  };

  myDateInit: boolean = true;
  model: IMyDateModel = null;

  // For chartjs
  tsLabels: any[];
  barChartColors:any = ['#3c8dbc', '#00a65a', '#f56954']
  metersData:any;
  initialDate:any;


  public barChartType: ChartType;
  public barChartLegend:boolean;
  public barChartLabels: Label[];
  public barChartOptions: ChartOptions;
  public barChartData: ChartDataSets[];

  isActive:[boolean,boolean,boolean,boolean]; //Activated param (chart)

  constructor(
    private orgService: OrganizationsService, 
    private route: ActivatedRoute, 
    private plantsService: PlantsService,
    private http: HttpClient,
    private logsService: LogsService,
    private measService: MeasuresService) {
      
      this.route.queryParams.subscribe(params => {
        this.organizationId = params['id'];
      });
      
      Swal.fire({
        allowOutsideClick: false,
        type: 'info',
        text: 'Espere por favor...'
      });
      Swal.showLoading();
      
  }

  @ViewChild("baseChart",null) chart: BaseChartDirective;

  ngOnInit() {

    // Default date is today and set it on a string var and initialize dateRange plugin
    this.initialDate = new Date().toISOString().slice(0, 10);
    if (this.myDateInit) {
      let begin: Date = new Date();
      this.model = {
        isRange: false, 
        singleDate: {
          date: {
            year: begin.getFullYear(), month: begin.getMonth() + 1, day: begin.getDate()
          }
        }
      };
    }
    // Initialize on load
    this.isActive = [false, false, false, false];

    let plants = this.plantsService.getAllAssets().subscribe(res => {
      this.listAssets = res["data"]["assets"];
      this.view = "month";
      if (this.organizationId == undefined){
        this.organizationId = this.listAssets[0].id;
      }
      this.onMeasureClickRange(this.view, this.initialDate);

      let energy_produced = this.logsService.getEnergySummaryByAsset(this.organizationId).subscribe(resp => {
        this.eProduced = resp["data"]["energy"];//results[1];
        this.energyDay = this.eProduced.today.total_energy_kWh;
        this.energyWeek = this.eProduced.thisWeek.total_energy_kWh > 0 ? (this.eProduced.thisWeek.total_energy_kWh/1000).toFixed(2) : this.eProduced.thisWeek.total_energy_kWh
        this.energyMonth = this.eProduced.thisMonth.total_energy_kWh > 0 ? (this.eProduced.thisMonth.total_energy_kWh/1000).toFixed(2) : this.eProduced.thisMonth.total_energy_kWh
        this.energyYear = this.eProduced.lifeTime.total_energy_kWh > 0 ? (this.eProduced.lifeTime.total_energy_kWh/1000).toFixed(2) : this.eProduced.lifeTime.total_energy_kWh
      });

    }, (err) => {
      Swal.fire({
        type: 'error',
        title: 'Error en el servidor',
        text: "No su pudo obtener la informacion"
      });
    });

    //this.chartjs = true;
    setTimeout(()=>{
      Swal.close();
    }, 2700);
  }
 
  // Default check asset dropdown if a value is equal to an assetID
  isSelected(){
    if(this.organizationId!=undefined){
      return true;
    }
    else{
      return false;
    }
  }

  // Trigger again the chart with the selected assetID
  onChangeObj(event:any) {
    this.organizationId = event.target.value;
    this.onMeasureClickRange(this.view, this.initialDate, this.organizationId);
  }
  

  // Change the date range of the chart, according to the selected view (daily, weekly, ...)
  onDateChanged(event: IMyDateModel) {
    let endDate = `${event.singleDate.date.year}-${event.singleDate.date.month}-${event.singleDate.date.day}`;
    this.initialDate  = endDate;
    switch (this.view)
    { 
      case "day": 
        this.onMeasureClickRange(this.view, endDate);
        break; 
      case "week": 
        this.onMeasureClickRange(this.view, endDate);
        break; 
      case "month": 
        this.onMeasureClickRange(this.view, endDate);
        break; 
      case "year":
        this.onMeasureClickRange(this.view, endDate);
        break;
      default: 
        console.log("nada");
    } 
  }

  // Draw a measure chart using chartjs, given some params, view, for daily, weekly, monthly or yearly measures;
  // measureDate, for a date range given a view and a paramID, for an specific assetID selected in the dropdown  
  onMeasureClickRange(view:string, measureDate?:string, paramId?:string): void {
    Swal.fire({
      allowOutsideClick: false,
      type: 'info',
      text: 'Espere por favor...'
    });
    Swal.showLoading();
    this.view = view;

    // Chart (re)initialize, to prevent double load on changing date range or views
    if (this.chart1 != undefined){
      this.chart1.destroy();
    }
    this.chart1 = undefined;
    
    let dateRange:string;
    if (measureDate === undefined){
      dateRange = this.initialDate;
    }
    else {
      dateRange = measureDate;
    }

    // Set default assetID if paramId doesn't come in the function call
    let assetId:string;
    if (paramId === undefined){
      assetId = this.listAssets[0]["id"]; // Grab the first object
    }
    else {
      assetId = paramId;
    }
    
    // Select an interval according to the API permitted param
    let interval:string;
    switch (view)
    { 
      case "day": 
        interval = "1D";
        this.isActive = [true, false, false, false];
        break; 
      case "week": 
        interval = "7D";
        this.isActive = [false, true, false, false];
        break; 
      case "month":
        interval = "1M";
        this.isActive = [false, false, true, false];
        break; 
      case "mtd": //TO DO
        interval = "MTD";
        break;
      case "year":
        interval = "YTD";
        this.isActive = [false, false, false, true];
        break;
      default: 
        console.log("nada");
    }  

    this.logsService.getEnergyProducedByParams(assetId,interval,dateRange).toPromise()
    .then((data: any) => {
      this.metersData = [];      
      this.metersKeys = Object.keys(data["data"]["dataset"]);

      // Get all the values according to each index (meter) 
      this.metersValues = Object.values(data["data"]["dataset"]);

      // Get the keys of those values
      let meterKeys2 = Object.keys(this.metersValues);

      for (let prop in meterKeys2) { 
        //let label = localStorage.getItem("email") == "inverlec@grupomerelec.com" ? `INVERLEC ${prop}` : this.metersValues[prop]["label"];
        let label = this.metersValues[prop]["label"];
        let measure_values = Object.values(this.metersValues[prop]["data"].map(obj => obj.total_energy_kWh).reverse())
        this.metersData.push({"label": label, backgroundColor: this.barChartColors[prop], data: measure_values });
      }

      switch (view){
        case "day": 
          this.barChartLabels = this.metersValues[0]["data"].map(obj => formatDate(obj.dateMax, 'hh:mm:ss','es-Es','-0600')).reverse();
          break; 
        case 'week':
          this.barChartLabels = this.metersValues[0]["data"].map(obj => formatDate(obj.dateMax, 'EEEE dd','es-Es','-0600')).reverse();
          break;
        case "year":
          this.barChartLabels = this.metersValues[0]["data"].map(obj => formatDate(obj.dateMax, 'MM/yyyy','es-Es','-0600')).reverse();
          break;
        default: 
          this.barChartLabels = this.metersValues[0]["data"].map(obj => formatDate(obj.dateMax, 'dd/MM','es-Es','-0600')).reverse(); 
      }

      this.chart1 = new Chart('canvas', {
        type: 'bar',
        options: {
          title: {
            display: true,
          },
          tooltips: {
            mode: 'index',
            callbacks: {
              // Get the total of the energy produced in every point and show it in the hover tooltip
              label: function (tooltipItem, data) { 
                var label = data.datasets[tooltipItem.datasetIndex].label || '';
                var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                var total = 0;

                for (var i = 0; i < data.datasets.length; i++)
                  total += +data.datasets[i].data[tooltipItem.index];

                if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
                  return label + " : " + value;
                }
                else {
                  return [label + " : " + value, "TOTAL : " + Math.round(total)];
                }
              }
            }         
          },
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            xAxes: [{
              stacked: true,
            }],
            yAxes: [{
              stacked: true
            }]
          }
        },
        data: {
          labels: this.barChartLabels,
          datasets: this.metersData,
        }, 
      });
      this.chartjs = true;
    });

    setTimeout(()=>{
      Swal.close();
    }, 1200)

  }

}
