import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatPaginator, MatPaginatorIntl } from '@angular/material/paginator';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatTableDataSource } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { lastValueFrom } from 'rxjs';
import { WorkflowService } from 'src/app/services/samwf/workflow.service';

@Component({
  selector: 'app-workflow-admin-advance',
  templateUrl: './workflow-admin-advance.component.html',
  styleUrls: ['./workflow-admin-advance.component.css'],
})
export class WorkflowAdminAdvanceComponent implements OnInit {
  data_empty = false;

  displayedColumns: string[] = ['name', 'module', 'created_at'];
  advance: any[] = [];

  dataSource = new MatTableDataSource<any>(this.advance);
  @ViewChild(MatPaginator) paginator: MatPaginator = new MatPaginator(
    new MatPaginatorIntl(),
    ChangeDetectorRef.prototype
  );
  constructor(
    private routerNavigate: ActivatedRoute,
    private router: Router,
    public dialog: MatDialog,
    private translate: TranslateService,
    private _samwfService: WorkflowService,
    private _snackBar: MatSnackBar
  ) {
    translate.setDefaultLang('es');
  }

  ngOnInit(): void {
    this.getRequestUser();
  }

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

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

  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];
    });
  }

  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.name.toString().toLowerCase().includes(filter) ||
        data.description.toString().toLowerCase().includes(filter) ||
        data.created_at.toString().includes(filter)
      );
    };
  }

  private async getRequestUser() {
    await lastValueFrom(this._samwfService.getRequestsAdvance(1)).then(
      (data: any) => {
        this.advance = data.response.workflow.tasks;
        this.dataSource.data = data.response.workflow.tasks;
        this.formatData(data.response.workflow.tasks);
        /*         this.dataSource.data = data.filter((e: any) => {
          e.created_at = e.created_at.slice(0, 10);
          return e;
        }); */

        this.dataSource.data.length > 0
          ? (this.data_empty = false)
          : (this.data_empty = true);
      },
      (error: any) => {
        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
  }

  formatData(workflow_tasks: any[]) {
    let arr: any[] = [];
    for (let index = 0; index < workflow_tasks.length; index++) {
      console.log('workflow de primer nivel');
      arr.push({
        tarea: workflow_tasks[index].name,
        workflow: 'Tarea principal',
        status: workflow_tasks[index].status,
      });
      if (workflow_tasks[index].workflow != null) {
        for (
          let indexAux = 0;
          indexAux < workflow_tasks[index].workflow.tasks.length;
          indexAux++
        ) {
          arr.push({
            tarea: workflow_tasks[index].workflow.tasks[indexAux].name,
            workflow: workflow_tasks[index].name,
            status: workflow_tasks[index].workflow.tasks[indexAux].status,
          });
          if (workflow_tasks[index].workflow.tasks[indexAux].workflow != null) {
            console.log('workflow de segundo nivel');
            for (
              let indexLevel3 = 0;
              indexLevel3 <
              workflow_tasks[index].workflow.tasks[indexAux].workflow.tasks
                .length;
              indexLevel3++
            ) {
              arr.push({
                tarea:
                  workflow_tasks[index].workflow.tasks[indexAux].workflow.tasks[
                    indexLevel3
                  ].name,
                workflow: workflow_tasks[index].workflow.tasks[indexAux].name,
                status:
                  workflow_tasks[index].workflow.tasks[indexAux].workflow.tasks[
                    indexLevel3
                  ].status,
              });
              if (
                workflow_tasks[index].workflow.tasks[indexAux].workflow.tasks[
                  indexLevel3
                ].workflow != null
              ) {
                console.log('workflow de tercel nivel');
              }
            }
          }
        }
      }
    }
    console.log(arr);
    this.dataSource.data = arr;
  }
}
