import { Component, ViewChild, AfterViewInit, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { MatDialog } from '@angular/material/dialog';
import { lastValueFrom } from 'rxjs';
import { WorkflowService } from 'src/app/services/samwf/workflow.service';
import { filter } from '@syncfusion/ej2/maps';
import { TasksJSONInterface } from '../../interfaces/samwf/tasks-json-interface';
import { MatSnackBar } from '@angular/material/snack-bar';
import { TaskModuleFormComponent } from './task-module-form/task-module-form.component';

@Component({
  selector: 'app-tasks-module',
  templateUrl: './tasks-module.component.html',
  styleUrls: ['./tasks-module.component.css'],
})
export class TasksModuleComponent implements OnInit {
  loading: Boolean = false;
  tasks: any[] = [];
  data_empty = false;
  filter_empty = false;

  displayedColumns: string[] = [
    'name_task',
    'module',
    'workflow',
    'isAvailable',
    'notification',
    'actions',
  ];

  minDate: Date;
  maxDate: Date;
  modules: any[] = [];
  filterSendDate: any;
  filterModule: any;
  workflowsDataBase: any[] = [];
  dataSource = new MatTableDataSource<any>(this.tasks);

  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor(
    public dialog: MatDialog,
    private router: Router,
    private translate: TranslateService,
    private _samwfService: WorkflowService,
    private _snackBar: MatSnackBar
  ) {
    const currentYear = new Date().getFullYear();
    this.minDate = new Date(currentYear - 2, 0, 0);
    this.maxDate = new Date(currentYear + 1, 0, 0);
    this.dataSource.data.length > 0
      ? (this.data_empty = false)
      : (this.data_empty = true);
    translate.setDefaultLang('es');
  }

  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.content.date.toString().toLowerCase().includes(filter) ||
        data.content.workflow.toString().toLowerCase().includes(filter) ||
        data.content.task.toLowerCase().includes(filter)
      );
    };
  }

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

  ngOnInit(): void {
    this.getTasks();
    this.getWorkflows();
  }

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

  async openDialogTaskForm(action: string, item: any) {
    let dataAux = {
      action: action,
      item: item,
      workflows: this.workflowsDataBase,
      modules: this.modules,
    };
    const dialogRef = this.dialog.open(TaskModuleFormComponent, {
      data: dataAux,
    });

    dialogRef.afterClosed().subscribe((result: any) => {
      if (result) {
        if (action == 'Registrar') {
          console.log(result);
          this.registerTask(result);
        } else {
          console.log(result);
          this.editTask(item.id, result);
        }
      }
    });
  }

  async disableTask(idTask: any) {
    await lastValueFrom(this._samwfService.disableTaskModule(idTask)).then(
      (data: any) => {
        if (!data.error) {
          this._snackBar.open('!Actualización de tarea exitoso!', 'Cerrar', {
            duration: 3000,
          });
        }
        this.ngOnInit();
      },
      (error: any) => {
        console.error(error);

        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
  }

  private async getWorkflows() {
    await lastValueFrom(this._samwfService.getWorkflows()).then(
      (data: any) => {
        this.workflowsDataBase = data;
      },
      (error: any) => {
        console.error(error);

        this.loading = true;
        this._snackBar.open(
          'Continuamos buscando la información, espere un momento.',
          'Cerrar',
          { duration: 3000 }
        );
      }
    );
  }

  private async registerTask(task: TasksJSONInterface) {
    await lastValueFrom(this._samwfService.registerTask(task)).then(
      (data: any) => {
        if (!data.error) {
          this._snackBar.open('!Registro de tarea existoso!', 'Cerrar', {
            duration: 3000,
          });
        }
      },
      (error: any) => {
        console.error(error);

        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
    this.ngOnInit();
  }

  private async editTask(idTask: any, task: TasksJSONInterface) {
    console.log(task);

    await lastValueFrom(this._samwfService.updateTask(idTask, task)).then(
      (data: any) => {
        if (!data.error) {
          this._snackBar.open('!Modificación de tarea existoso!', 'Cerrar', {
            duration: 3000,
          });
        }
      },
      (error: any) => {
        console.log(error);

        this._snackBar.open(error.message, 'Cerrar', { duration: 3000 });
      }
    );
    this.ngOnInit();
  }

  private formatDate(date: Date) {
    var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
  }

  private async getTasks() {
    await lastValueFrom(this._samwfService.getTasks()).then(
      (data: any) => {
        this.dataSource.data = data;
        this.tasks = data;
        console.log(data);
        this.loading = false;

        this.dataSource.data.length > 0
          ? (this.data_empty = false)
          : (this.data_empty = true);
      },
      (error: any) => {
        console.error(error);
        this.loading = true;
        this._snackBar.open(
          'Continuamos buscando la información, espere un momento.',
          'Cerrar',
          { duration: 3000 }
        );
      }
    );

    await lastValueFrom(this._samwfService.getModules()).then(
      (data: any) => {
        this.modules = data;
      },
      (error: any) => {
        console.error(error);

        this.loading = true;
        this._snackBar.open(
          'Continuamos buscando la información, espere un momento.',
          'Cerrar',
          { duration: 3000 }
        );
      }
    );
  }
}
