import {
  Component,
  ViewChild,
  AfterViewInit,
  OnInit,
  ChangeDetectorRef,
} from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { MatDialog } from '@angular/material/dialog';
import { WorkflowService } from 'src/app/services/samwf/workflow.service';
import { isNullOrUndefined } from '@syncfusion/ej2-base';
import { lastValueFrom } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ResponseData } from 'src/app/interfaces/response-data';
import { HttpErrorResponse } from '@angular/common/http';

@Component({
  selector: 'app-workflow-versions-history',
  templateUrl: './workflow-versions-history.component.html',
  styleUrls: ['./workflow-versions-history.component.css'],
})
export class WorkflowVersionsHistoryComponent implements AfterViewInit {
  loading: Boolean = false;
  data_empty = false;
  idWorkflow: any;
  workflows_versions: any[] = [];
  displayedColumns: string[] = ['name', 'sequence', 'isAvailable'];

  dataWorkflow: any[] = [];
  workflow_comparative: any[] = [];
  selectedOption: any;

  showOriginal: boolean = false;
  showComparative: boolean = false;
  showMessage: boolean = true;
  showMessageComparative: boolean = true;
  dataOriginal: boolean = false;
  dataComparative: boolean = false;
  showPaginator: boolean = false;
  showPaginatorAux: boolean = false;

  public btnSmall: boolean = false;
  public card_size = 'card-size-normal mat-elevation-z8';

  public dataSource: MatTableDataSource<any>;
  public dataSourceComparative: MatTableDataSource<any>;

  @ViewChild(MatPaginator) paginator!: MatPaginator;

  @ViewChild(MatPaginator) paginatorComparative!: MatPaginator;

  constructor(
    private routerActivate: ActivatedRoute,
    private translate: TranslateService,
    private router: Router,
    private _samwfService: WorkflowService,
    private _snackBar: MatSnackBar
  ) {
    this.idWorkflow = this.routerActivate.snapshot.paramMap.get('id');
    translate.setDefaultLang('es');

    this.dataSource = new MatTableDataSource();
    this.dataSourceComparative = new MatTableDataSource();

    this.getVersionsByWorkflow();
  }

  ngOnInit(): void {}

  updatePaginator() {
    this.translate.get('paginador').subscribe((data: any) => {
      this.dataSource.paginator = this.paginator;
      this.paginator!._intl.itemsPerPageLabel = data[0];
      this.paginator!._intl.firstPageLabel = data[1];
      this.paginator!._intl.lastPageLabel = data[2];
      this.paginator!._intl.nextPageLabel = data[3];
      this.paginator!._intl.previousPageLabel = data[4];
    });

    this.translate.get('paginador').subscribe((data: any) => {
      this.dataSourceComparative.paginator = this.paginatorComparative;
      this.paginatorComparative._intl.itemsPerPageLabel = data[0];
      this.paginatorComparative._intl.firstPageLabel = data[1];
      this.paginatorComparative._intl.lastPageLabel = data[2];
      this.paginatorComparative._intl.nextPageLabel = data[3];
      this.paginatorComparative._intl.previousPageLabel = data[4];
    });
  }

  ngAfterViewInit(): void {
    this.dataSource.paginator = this.paginator;
    this.dataSourceComparative.paginator = this.paginatorComparative;

    /* this.translate.get('paginador').subscribe((data: any) => {
      this.dataSource.paginator = this.paginator;
      this.paginator!._intl.itemsPerPageLabel = data[0];
      this.paginator!._intl.firstPageLabel = data[1];
      this.paginator!._intl.lastPageLabel = data[2];
      this.paginator!._intl.nextPageLabel = data[3];
      this.paginator!._intl.previousPageLabel = data[4];
    });

    this.translate.get('paginador').subscribe((data: any) => {
      this.dataSourceComparative.paginator = this.paginatorComparative;
      this.paginatorComparative._intl.itemsPerPageLabel = data[0];
      this.paginatorComparative._intl.firstPageLabel = data[1];
      this.paginatorComparative._intl.lastPageLabel = data[2];
      this.paginatorComparative._intl.nextPageLabel = data[3];
      this.paginatorComparative._intl.previousPageLabel = data[4];
    }); */

    if (window.innerWidth <= 721) {
      this.btnSmall = true;
      this.card_size = 'card-size-small';
    } else if (window.innerWidth > 721) {
      this.btnSmall = false;
      this.card_size = 'card-size-normal mat-elevation-z8';
    }
  }
  backToWorkflows() {
    this.router.navigate(['sam/workflow']);
  }

  changeComparative(event: any) {
    this.showMessageComparative = false;
    if (event.version != 'v1') {
      if (isNullOrUndefined(event.workflowChanges?.tasks)) {
        this.dataSourceComparative.data = [];
        this.dataComparative = true;
        this.showComparative = true;
        this.showPaginatorAux = false;
      } else {
        if (event.workflowChanges.isForm == true) {
          this.dataWorkflow = event.workflowChanges.fields;
          this.dataSourceComparative.data = event.workflowChanges.fields;
        } else {
          this.dataComparative = event.workflowChanges.tasks;
          this.dataSourceComparative.data = event.workflowChanges.tasks;
        }
        this.dataComparative = false;
        this.showPaginatorAux = true;
      }
    } else {
      this.showPaginatorAux = false;
      this.dataSourceComparative.data = [];
      this.dataComparative = true;
    }
  }

  changeOriginal(event: any) {
    this.showMessage = false;
    if (event.version != 'v1') {
      if (isNullOrUndefined(event.workflowChanges?.tasks)) {
        this.dataSource.data = [];
        this.dataOriginal = true;
        this.showOriginal = true;
        this.showPaginator = false;
      } else {
        if (event.workflowChanges.isForm == true) {
          this.dataWorkflow = event.workflowChanges.fields;
          this.dataSource.data = event.workflowChanges.fields;
        } else {
          this.dataWorkflow = event.workflowChanges.tasks;
          this.dataSource.data = event.workflowChanges.tasks;
        }
        this.dataOriginal = false;
        this.showPaginator = true;
      }
    } else {
      this.dataOriginal = true;
      this.dataSource.data = [];
      this.showPaginator = false;
    }
  }

  private async getVersionsByWorkflow() {
    await lastValueFrom(
      this._samwfService.getVersionsWorkflow(this.idWorkflow)
    ).then(
      (data: ResponseData) => {
        this.workflows_versions = data.response.filter((object: any) => {
          return object.version != 'v1';
        });
      },
      (error: HttpErrorResponse) => {
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
  }

  public applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }

  public onResize(event: any) {
    if (event.target.innerWidth <= 721) {
      this.btnSmall = true;
      this.card_size = 'card-size-small';
    } else if (event.target.innerWidth > 721) {
      this.btnSmall = false;
      this.card_size = 'card-size-normal mat-elevation-z8';
    }
  }
}
