import { Component, OnInit, AfterViewInit } from '@angular/core';
import { LinealChart } from 'src/app/models/Charts/lineal-chart.model';
import { MinimizeNumberPipe } from 'src/app/pipes/minimize-number.pipe';
import { BarChart } from 'src/app/models/Charts/bar-chart.model';
import { PieChart } from 'src/app/models/Charts/pie-chart.model';
import { MiniInfo } from 'src/app/models/Charts/mini-info.model';

import { SubscriptionService } from 'src/app/services/subscription.service';
import { SubscriptionSelection } from 'src/app/models/subscription-selection.model';
import { UtilsService } from 'src/app/services/utils.service';
import { DashboardService } from 'src/app/pipes/dashboard.service';
import { UserSubscription } from 'src/app/models/user-subscription.model';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit, AfterViewInit {

  subscriptionSelection:SubscriptionSelection;
  company_id:number;
  box_id:number;

  date_fi: Date = new Date();
  date_ini: Date;// = new Date('1990-01-01');

  ingresos_chart: LinealChart;
  actividad_chart: BarChart;
  consumo_chart: BarChart;
  clases_impartidas: LinealChart;
  suscripcions_tarifa: PieChart;
  ocupacion_box: BarChart;
  barMaxWidth = 50;
  mini_ingresos: MiniInfo;
  mini_news: MiniInfo;
  mini_olds: MiniInfo;
  max_min_users:any[];
  toolTips:string[];
  subscriptions_prorroga:UserSubscription[];
  subscriptions_ending:UserSubscription[];

  loading:boolean = true;

  coach = false;
  
  constructor(private subscriptionService: SubscriptionService,
              private utilsService: UtilsService,
              private dashboardService: DashboardService) { }

  ngOnInit(): void {
    this.date_ini = new Date(this.date_fi.getFullYear(), this.date_fi.getMonth(), 1);
  }

  ngAfterViewInit() {
    this.subscriptionService.currentSubscription.subscribe( s => {
      if (s) {
        this.subscriptionSelection = s;
        this.coach = (s.role.id == 4);
        if (s.box) {
          this.company_id = s.box.company_id;
          this.box_id = s.box.id;
        } else {
          this.company_id = s.company.id;
          this.box_id = null;
        }

        this.fetchData();
      }
    });
  }

  refresh() {
    this.dashboardService.deleteResponse();
    this.fetchData();
  }

  fetchData() {
    if(this.date_ini>this.date_fi) this.date_fi = this.date_ini;
    this.loading = true;
    this.allDataToNull();
    
    this.dashboardService.getDashboardInfo(this.company_id, this.box_id, this.dateFormat(this.date_ini), this.dateFormat(this.date_fi)).subscribe(
      data => {
        this.dashboardService.pushResponse(this.company_id, this.box_id, this.dateFormat(this.date_ini), this.dateFormat(this.date_fi),data)
        if (data.ingresos) {
          this.initIngresosChart(data.ingresos.chart);
          this.mini_ingresos = new MiniInfo((data.ingresos.total.total + ' ' + data.ingresos.total.units),'brutos',data.ingresos.evolution,this.date_ini,1);  
        }
        if (data.actividad_usuarios) {
          this.mini_news = new MiniInfo(data.actividad_usuarios.new.number,'usuarios nuevos',data.actividad_usuarios.new.evolution,this.date_ini,2);
          this.mini_olds = new MiniInfo(data.actividad_usuarios.old.number,'usuarios perdidos',data.actividad_usuarios.old.evolution,this.date_ini,3);
        }
        if (data.actividad_box && data.actividad_box.length>0) {
          this.initActividadEnElBox(data.actividad_box);
        }
        if (data.consumo_creditos) {
          this.initConsumoCreditos(data.consumo_creditos);
        }
        if (data.max_min_users && data.max_min_users.length>0) {
          this.max_min_users = data.max_min_users;
        }
        if (data.clases_impartidas && data.clases_impartidas.length>0) {
          this.initClasesImpartidas(data.clases_impartidas);
        }
        if (data.subscripciones_tarifa && data.subscripciones_tarifa.length>0) {
          this.initSusctipcionsPerTarifa(data.subscripciones_tarifa);
        }
        if (data.ocupacio_box && data.ocupacio_box.length>0) {
          this.initOcupacionBox(data.ocupacio_box);
        }
        if (data.tool_tips) {
          this.toolTips = data.tool_tips;
        }
        this.subscriptions_ending = Object.values(data.subscriptions_ending);
        this.subscriptions_prorroga = Object.values(data.subscriptions_prorroga);

        this.loading = false;
      }
    );
  }

  private allDataToNull() {
    this.ingresos_chart = null;
    this.actividad_chart = null;
    this.consumo_chart = null;
    this.clases_impartidas = null;
    this.suscripcions_tarifa = null;
    this.ocupacion_box = null;
    this.barMaxWidth = null;
    this.mini_ingresos = null;
    this.mini_news = null;
    this.mini_olds = null;
    this.max_min_users = null;
    this.subscriptions_ending = null;
    this.subscriptions_prorroga = null;
  }

  initIngresosChart(results) {
    this.ingresos_chart = new LinealChart();
    this.ingresos_chart.showLegend = false;
    this.ingresos_chart.showXAxisLabel = false;
    this.ingresos_chart.showYAxisLabel = false;
    this.ingresos_chart.colorScheme.domain = this.utilsService.getColorsArray();
    this.ingresos_chart.results = results;
  }

  initActividadEnElBox(results) {
    this.actividad_chart = new BarChart();
    this.actividad_chart.showLegend = false;
    this.actividad_chart.showXAxisLabel = false;
    this.actividad_chart.showYAxisLabel = false;
    this.actividad_chart.results = results;
  }

  initConsumoCreditos(results) {
    this.consumo_chart = new BarChart();
    this.consumo_chart.showLegend = false;
    this.consumo_chart.showXAxisLabel = false;
    this.consumo_chart.showYAxisLabel = false;
    this.consumo_chart.results = results;
  }

  initClasesImpartidas(results) {
    this.clases_impartidas = new LinealChart();
    this.clases_impartidas.showLegend = false;
    this.clases_impartidas.showXAxisLabel = false;
    this.clases_impartidas.showYAxisLabel = false;
    this.clases_impartidas.colorScheme.domain = this.utilsService.getColorsArray();
    this.clases_impartidas.results = results;
  }

  initSusctipcionsPerTarifa(results) {
    this.suscripcions_tarifa = new PieChart();
    this.suscripcions_tarifa.legendPosition = 'below';
    this.suscripcions_tarifa.colorScheme.domain = this.utilsService.getColorsArray();
    this.suscripcions_tarifa.results = results;
  }

  initOcupacionBox(results) {
    this.ocupacion_box = new BarChart();
    this.ocupacion_box.showLegend = false;
    this.ocupacion_box.showXAxisLabel = false;
    this.ocupacion_box.showYAxisLabel = false;
    this.ocupacion_box.results = results;
  }

  onActivate(data): void {
    // console.log('Activate', JSON.parse(JSON.stringify(data)));
  }

  onDeactivate(data): void {
    // console.log('Deactivate', JSON.parse(JSON.stringify(data)));
  }

  dateFormat(date: Date) {
    if (!date) return null;
    const month = (date.getMonth()+1)<=9 ? '0'+(date.getMonth()+1) : (date.getMonth()+1);
    const day = date.getDate()<=9 ? '0'+date.getDate() : date.getDate()
    return date.getFullYear() + '-' + month + '-' + day;
  }

  axisFormatEuro(val) {
    return MinimizeNumberPipe.prototype.transform(parseInt(val.toLocaleString())) + ' €';
  }

  axisFormat(val) {
    return MinimizeNumberPipe.prototype.transform(parseInt(val.toLocaleString()));
  }

  axisFormatPercentatge(val) {
    return val.toLocaleString() + '%';
  }

  axisFormatRound(val) {
    return Math.round(parseInt(val.toLocaleString()))
  }

  onSelect(event) {

  }

}
