import { MatSnackBar } from '@angular/material/snack-bar';
import { ChartsService } from './../charts.service';
import { LoadingService } from 'src/app/core/loading.service';
import { AuthState } from './../../auth/store/auth.reducers';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { ChartsFeatureState, ChartsState } from './../store/charts.reducers';
import { Component, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { Store } from '@ngrx/store';
import { Chart } from '../model/Chart.model';
import * as html2canvas from 'html2canvas';

@Component({
  selector: 'app-chart-detail',
  templateUrl: './chart-detail.component.html',
  styleUrls: ['./chart-detail.component.scss']
})
export class ChartDetailComponent implements OnInit, OnDestroy {

  chart: Chart;
  userId: number;

  pinnable: boolean = false;
  unpinnable: boolean = false;

  exportInProgress: boolean = false;

  private chartStoreSubscription: Subscription;
  private userStoreSubscription: Subscription;

  constructor(
    private route: ActivatedRoute, 
    private router: Router, 
    private loadingService: LoadingService,
    private chartsService: ChartsService,
    private snackBar: MatSnackBar,
    private store: Store<ChartsFeatureState>
  ) {
    let id = this.route.snapshot.params['id'];
    if (!id)
      this.router.navigate(['/charts']);
    else {
      this.userStoreSubscription = store.select('authState').subscribe(
        (state: AuthState) => {
          if (state.user){
            this.userId = state.user.id;
          }
        }
      );
      this.chartStoreSubscription = store.select('charts').subscribe(
        (state: ChartsState) => {
          if (!this.chart){
            this.chart = this.getChartFromState(+id, state);
            if (!this.chart){
              this.chartsService.requestChartMeta(+id).subscribe(
                (chart: Chart) => {
                  this.chart = chart;
                },
                () => {
                  this.snackBar.open("Data pro tento graf se nepodařilo získat.", "zavřít", { duration: 2500 } );
                  this.router.navigate(['/charts']);
                }
              );
            }
          }
          if (state.privateCharts){
            let addedCharts: Chart[] = state.privateCharts.addedCharts;
            if (addedCharts.findIndex((chart: Chart) => { return chart.id === +id}) > -1)
              this.unpinnable = true;
            else
              this.pinnable = true;
          }
        }
      );
    }
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.chartStoreSubscription.unsubscribe();
    this.userStoreSubscription.unsubscribe();
  }

  private onExportClick(elementToExport: any){
    this.exportInProgress = true;
    setTimeout(() => {
      html2canvas(elementToExport).then(canvas => {
        this.exportInProgress = false;
        this.chartsService.downloadCanvas(canvas);
      }
    )}, 0);
  }

  private onPinChart(chartId: number){
    this.chartsService.requestPinChart(chartId);
    this.pinnable = false;
  }

  private onUnpinClick(chartId: number){
    this.chartsService.requestUnpinChart(chartId);
    this.unpinnable = false;
  }

  private onDeleteClick(chartId: number){
    this.chartsService.requestDeleteChart(chartId, true);
  }

  private getChartFromState(chartId: number, state: ChartsState): Chart{
    let index: number;
    if (state.publicCharts){
      index = state.publicCharts.findIndex((chart) => { return chart.id === chartId });
      if (index > -1)
        return state.publicCharts[index];
    }
    if (state.privateCharts){
      index = state.privateCharts.addedCharts.findIndex((chart) => { return chart.id === chartId });
      if (index > -1)
        return state.privateCharts.addedCharts[index];
      index = state.privateCharts.usersCharts.findIndex((chart) => { return chart.id === chartId });
      if (index > -1)
        return state.privateCharts.usersCharts[index];
    }
    return null;
  }
}
