import { Component, ViewChild, AfterViewInit, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } 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';

@Component({
  selector: 'app-workflow-versions-history',
  templateUrl: './workflow-versions-history.component.html',
  styleUrls: ['./workflow-versions-history.component.css'],
})
export class WorkflowVersionsHistoryComponent implements OnInit {
  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;

  dataSource = new MatTableDataSource<any>(this.dataWorkflow);

  dataSourceComparative = new MatTableDataSource<any>(
    this.workflow_comparative
  );

  @ViewChild('paginator') paginator: MatPaginator;
  @ViewChild('paginatorComparative') 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.data.length > 0
      ? (this.data_empty = false)
      : (this.data_empty = true);
    this.obtener();
  }

  ngOnInit(): void {}

  private async obtener() {
    await lastValueFrom(
      this._samwfService.getVersionsWorkflow(this.idWorkflow)
    ).then(
      (data: any) => {
        this.workflows_versions = data;
      },
      (error: any) => {
        console.log(error);
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
  }

  ngAfterViewInit(): void {
    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];
    });

    this.dataSource.filterPredicate = function (data, filter: string): boolean {
      return (
        data.fecha_envio.toString().toLowerCase().includes(filter) ||
        data.usuario_remitente.nombre
          .toString()
          .toLowerCase()
          .includes(filter) ||
        data.modulo.nombre_modulo.toLowerCase().includes(filter)
      );
    };
  }

  applyFilter(filterValue: any) {
    this.dataSource.filter = filterValue.target.value.trim().toLowerCase();
  }

  backToWorkflows() {
    this.router.navigate(['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 {
        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 {
        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;
    }
  }
}
