import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import {
  MatDialog,
  MatDialogRef,
  MAT_DIALOG_DATA,
} from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { ActivatedRoute } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { lastValueFrom } from 'rxjs';
import { WorkflowService } from 'src/app/services/samwf/workflow.service';
import { WorkflowComponent } from '../../workflow.component';
import { TaskFormValidatorsComponent } from './task-form-validators/task-form-validators.component';

@Component({
  selector: 'app-task-module-form',
  templateUrl: './task-module-form.component.html',
  styleUrls: ['./task-module-form.component.css'],
})
export class TaskModuleFormComponent implements OnInit {
  formGroup: FormGroup;
  value: any[] = [];
  notificationValue: any[] = [];
  selectAll = false;
  desplegarCondicionales: boolean = false;
  posicion = 0;
  secuenciaNueva: number = 0;
  arrIndex = 0;

  workflowsBD: any[] = [];
  modules: any[] = [];
  tasksData: any[] = [];
  formFields: any[] = [];

  storesNotify = [
    { id: 0, name: 'Juan Alvarez' },
    { id: 1, name: 'Alan Carranza' },
    { id: 2, name: 'Jean Benitez' },
    { id: 4, name: 'Emmanuel Estrada' },
  ];

  storesValidate = [
    { id: 0, name: 'Juan Alvarez' },
    { id: 1, name: 'Alan Carranza' },
    { id: 2, name: 'Jean Benitez' },
    { id: 4, name: 'Emmanuel Estrada' },
  ];

  constructor(
    public dialog: MatDialog,
    public dialogRef: MatDialogRef<any>,
    private _snackBar: MatSnackBar,
    private _samwfService: WorkflowService,
    private activatedRoute: ActivatedRoute,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private translate: TranslateService
  ) {
    translate.setDefaultLang('es');
    console.log(this.data.item);

    this.modules = this.data.modules;
    this.workflowsBD = this.data.workflows;
    this.formGroup = this.createFormGroup();
  }

  ngOnInit(): void {}

  private createFormGroup() {
    if (this.data.action == 'Registrar') {
      return new FormGroup({
        name: new FormControl(''),
        description: new FormControl(''),
        sequence: new FormControl(null),
        nextSequence: new FormControl(null),
        changeSequence: new FormControl(null),
        employeesNotify: new FormControl([], Validators.required),
        employeesValidate: new FormControl([]),
        validationRules: new FormControl([]),
        status: new FormControl('Pending'),
        isAvailable: new FormControl(true),
        isValidated: new FormControl(false),
        notification: new FormControl(''),
        isConditional: new FormControl(null),
        id_workflow: new FormControl(null),
        id_module: new FormControl(null),
      });
    } else {
      let positionWorkflow = this.workflowsBD.findIndex((object: any) => {
        return object.id == this.data.item.id_workflow;
      });

      let positionModule = this.modules.findIndex((object: any) => {
        return object.id == this.data.item.id_module;
      });

      return new FormGroup({
        name: new FormControl(this.data.item.name),
        description: new FormControl(this.data.item.description),
        sequence: new FormControl(this.data.item.sequence),
        nextSequence: new FormControl(this.data.item.nextSequence),
        changeSequence: new FormControl(this.data.item.changeSequence),
        employeesNotify: new FormControl(
          this.getBoxesNotify(),
          Validators.required
        ),
        employeesValidate: new FormControl(this.getBoxesValidate()),
        validationRules: new FormControl(this.data.item.validationRules),
        status: new FormControl(this.data.item.status),
        isAvailable: new FormControl(this.data.item.isAvailable),
        isValidated: new FormControl(this.data.item.isValidated),
        notification: new FormControl(this.data.item.notification),
        isConditional: new FormControl(this.data.item.isConditional),
        id_workflow: new FormControl(
          positionWorkflow > -1
            ? this.workflowsBD[positionWorkflow].id
            : 'Sin workflow'
        ),
        id_module: new FormControl(
          positionModule > -1 ? this.modules[positionModule].id : 'Sin modulo'
        ),
      });
    }
  }

  enviar(item: any) {
    if (item.id_workflow == null || item.id_workflow == 'Sin workflow') {
      delete item.id_workflow;
    }

    if (item.id_module == null || item.id_module == 'Sin modulo') {
      delete item.id_module;
    }

    console.log(item);

    item.notification = item.employeesNotify.length > 0 ? true : false;

    this.dialogRef.close(item);
  }

  valueChange(id: any) {
    if (this.value.indexOf(id) > -1) {
      const pos = this.value.indexOf(id);
      this.value.splice(pos, 1);
    } else {
      this.value.push(id);
    }
  }

  toggleAllSelection() {
    this.selectAll = !this.selectAll;
    if (this.selectAll == true) {
      this.value = this.storesNotify;
    } else {
      this.value = [];
    }
  }

  changeNotification(id: any) {
    if (this.notificationValue.indexOf(id) > -1) {
      const pos = this.notificationValue.indexOf(id);
      this.notificationValue.splice(pos, 1);
    } else {
      this.notificationValue.push(id);
    }
  }

  toggleNotificationSelection() {
    this.selectAll = !this.selectAll;
    if (this.selectAll == true) {
      this.notificationValue = this.storesValidate;
    } else {
      this.notificationValue = [];
    }
  }

  openDialogFields() {
    let dataAction = {
      action: this.data.action,
      item: this.data.item,
    };

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

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        if (this.data.action == 'Registrar') {
          console.log(result);
        } else {
          console.log(result);
        }
      }
    });
  }

  getBoxesNotify() {
    let arrIndex = [];
    for (
      let indexFor = 0;
      indexFor < this.data.item.employeesNotify.length;
      indexFor++
    ) {
      let index = this.storesNotify.findIndex(
        (element) => element.id == this.data.item.employeesNotify[indexFor].id
      );
      arrIndex.push(index);
    }

    let arrUsr: any[] = [];
    arrIndex.forEach((element) => {
      arrUsr.push(this.storesNotify[element]);
    });

    return arrUsr;
  }

  getBoxesValidate() {
    let arrIndex = [];
    for (
      let indexFor = 0;
      indexFor < this.data.item.employeesValidate.length;
      indexFor++
    ) {
      let index = this.storesValidate.findIndex(
        (element) => element.id == this.data.item.employeesValidate[indexFor].id
      );
      arrIndex.push(index);
    }

    let arrUsr: any[] = [];
    arrIndex.forEach((element) => {
      arrUsr.push(this.storesValidate[element]);
    });

    return arrUsr;
  }
  get name() {
    return this.formGroup.get('name');
  }

  get description() {
    return this.formGroup.get('description');
  }

  get sequence() {
    return this.formGroup.get('sequence');
  }

  get nextSequence() {
    return this.formGroup.get('nextSequence');
  }

  get changeSequence() {
    return this.formGroup.get('changeSequence');
  }
  get workflow() {
    return this.formGroup.get('workflow');
  }

  get employeesNotify() {
    return this.formGroup.get('employeesNotify');
  }

  get employeesValidate() {
    return this.formGroup.get('employeesValidate');
  }

  get validationRules() {
    return this.formGroup.get('validationRules');
  }

  get status() {
    return this.formGroup.get('status');
  }

  get isAvailable() {
    return this.formGroup.get('isAvailable');
  }

  get isValidated() {
    return this.formGroup.get('isValidated');
  }

  get notification() {
    return this.formGroup.get('notification');
  }

  get isConditional() {
    return this.formGroup.get('isConditional');
  }

  get id_workflow() {
    return this.formGroup.get('id_workflow');
  }

  get id_module() {
    return this.formGroup.get('id_module');
  }
}

/* sequence: new FormControl(''),
nextSequence: new FormControl(''),
changeSequence: new FormControl(''),
workflow: new FormControl(''),
employeesNotify: new FormControl(''),
employeesValidate: new FormControl(''),
validationRules: new FormControl(''),
status: new FormControl(''),
isAvailable: new FormControl(''),
isValidated: new FormControl(''),
notification: new FormControl(''),
isConditional: new FormControl(''),
id_workflow: new FormControl(''),
id_module: new FormControl(''),
}); */
