import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';

import { WorkflowPasosFormComponent } from './workflow-tasks-form/workflow-pasos-form.component';
import { WorkflowUsersComponent } from './workflow-users/workflow-users.component';
import { TranslationComponent } from '../../translation/translation.component';
import { TranslateService } from '@ngx-translate/core';
import { MaterialModule } from '../../material/material.module';
import { WorkflowService } from '../../services/SAMWF/workflow.service';
import { TaskInterface } from 'src/app/interfaces/SAMWF/task-interface';
import { TasksJSONInterface } from '../../interfaces/SAMWF/tasks-json-interface';
import { data } from '@syncfusion/ej2';
import { lastValueFrom, takeLast } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ResponseData } from 'src/app/interfaces/response-data';

@Component({
  selector: 'app-workflow-detail',
  templateUrl: './workflow-detail.component.html',
  styleUrls: ['./workflow-detail.component.css'],
})
export class WorkflowDetailComponent implements OnInit, MaterialModule {
  displayedColumns: string[] = [
    'sequence',
    'estatus',
    'process',
    'notification',
    'actions',
  ];

  data_empty = false;

  workflow: any = {};

  workflowObject: any = {};

  tasks: any = [];

  idWorkflow: any;

  @ViewChild(MatPaginator) paginator!: MatPaginator;
  dataSource = new MatTableDataSource<any>(this.tasks);

  constructor(
    private router: ActivatedRoute,
    public dialog: MatDialog,
    private routerNavigate: Router,
    private translate: TranslateService,
    private _samwfService: WorkflowService,
    private _snackBar: MatSnackBar
  ) {
    this.idWorkflow = this.router.snapshot.paramMap.get('id');
    this.getTasksWorkflow();

    translate.setDefaultLang('es');

    this.dataSource.data.length > 0
      ? (this.data_empty = false)
      : (this.data_empty = true);
  }

  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.dataSource.filterPredicate = function (data, filter: string): boolean {
      return (
        data.secuencia.toString().toLowerCase().includes(filter) ||
        data.estatus.toString().toLowerCase().includes(filter) ||
        data.accion.accion.toString().toLowerCase().includes(filter)
      );
    };
  }

  ngOnInit(): void {}

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

  // Dialogo
  async openDialogTaskForm(action: string, item: any = {}) {
    const sleep = (ms: number) =>
      new Promise((resolve) => setTimeout(resolve, ms));

    let processArr: any[] = [];

    await lastValueFrom(this._samwfService.getTasks()).then(
      (data: any) => {
        processArr = data;
      },
      (error: any) => console.log(error)
    );

    let data = item != null ? JSON.stringify(item) : null;
    let tasks_bd = processArr;

    this.sendArrayTasks(tasks_bd);
    this.routerNavigate.navigate([
      `/workflow/${this.idWorkflow}/tasksFlow`,
      { data, action },
    ]);
  }

  openDialogUsers(item: any) {
    let dataAction = {
      action: 'Usuarios',
      item: item,
    };

    const dialogRef = this.dialog.open(WorkflowUsersComponent, {
      data: dataAction,
    });

    dialogRef.afterClosed().subscribe((result) => {});
  }

  private async getTasksWorkflow() {
    await lastValueFrom(this._samwfService.getWorkflow(this.idWorkflow)).then(
      (data: any) => {
        this.workflowObject = data;

        this.workflow = data.tasks.filter(
          (object: any) => object.isAvailable != false
        );
        this.dataSource.data = data.tasks.filter(
          (object: any) => object.isAvailable != false
        );
        this.dataSource.data.length > 0
          ? (this.data_empty = false)
          : (this.data_empty = true);
      },
      (error: any) => console.log(error)
    );
  }

  sendArrayTasks(data: any) {
    this._samwfService.setArray(data);
  }

  backToWorkflows() {
    this.routerNavigate.navigate(['workflow']);
  }

  showDiagram() {
    this.router.params.subscribe((params) => {
      this.routerNavigate.navigate(['workflow/diagrama/', params['id']]);
    });
  }

  async disableTask(sequence: any, index: any) {
    this.workflowObject.tasks[index].isAvailable = false;
    this.workflowObject.tasks[index - 1].nextSequence =
      this.workflowObject.tasks[index + 1].sequence;

    await lastValueFrom(
      this._samwfService.updateWorkflow(this.workflowObject, this.idWorkflow)
    ).then(
      (data: ResponseData) => {
        if (!data.error) {
          this.ngOnInit();
          this._snackBar.open('!Actualización de workflow exitoso!', 'Cerrar', {
            duration: 3000,
          });
        }
      },
      (error) => {
        console.log(error);
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
    this.ngOnInit();
  }
}

/* objAux = {
  conditionalYes: this.tasksData[positionTaskYes],
  conditionalNo: this.tasksData[positionTaskNo],
  taskCurrent: this.tasksData[positAux].taskCurrent,
  indexYes: this.letras[this.indiceAux] + 1,
  indexNo: this.letras[this.indiceAux] + 2,
  indexPosition: this.tasksData[positAux].indexPosition,
}; */

/* const conditionalsAux = this.fb.group({
  conditionalYes: new FormControl(this.tasksData[positionTaskYes]),
  conditionalNo: new FormControl(this.tasksData[positionTaskNo]),
  taskCurrent: new FormControl(this.tasksData[positAux].taskCurrent),
  indexYes: new FormControl(this.letras[this.indiceAux] + 1),
  indexNo: new FormControl(this.letras[this.indiceAux] + 2),
  indexPosition: new FormControl(this.tasksData[positAux].indexPosition),
});
 */
