import { Component, Inject, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { UserResponse, UsersResponse } from '../../../interfaces/users.interface';
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from '@angular/material/dialog';
import { ComponentInformationCheckbox, DataDialogComponentCheckbox } from '../../../interfaces/forms-management/form-management.interface';
import { ResourcesService } from '../../../services/resources.service';
import { SystemAdminService } from '../../../services/system-admin.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { EncService } from '../../../services/enc.service';
import { lastValueFrom } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';
import { ExampleComponentComponent } from '../example-component/example-component.component';
import { AlertComponent } from '../../resources/dialogs/alert/alert.component';

@Component({
    selector: 'app-configurate-checkbox',
    templateUrl: './configurate-checkbox.component.html',
    styleUrl: './configurate-checkbox.component.css',
    standalone: false
})
export class ConfigurateCheckboxComponent implements OnInit {

  public isLoading: boolean;
  public formGroup: FormGroup;
  public arrUsers: UserResponse[];
  public arrColumns: string[];
  public arrIdentification: string[];
  public typeForm: 'R' | 'M';

  constructor(
    @Inject(MAT_DIALOG_DATA) public infoDataForm: DataDialogComponentCheckbox,
    public resourcesService: ResourcesService,
    private _systemAdminService: SystemAdminService,
    private _usersProfilesService: UsersProfilesService,
    private _encService: EncService,
    private _dialog: MatDialog,
    private _dialogRef: MatDialogRef<false | ComponentInformationCheckbox>,
  )  {
    this.isLoading = false;
    this.formGroup = this._createFormGroup();

    this.arrUsers = [];
    this.arrColumns = this.infoDataForm.COLUMNS;
    this.arrIdentification = this.infoDataForm.IDS;
    this.typeForm = this.infoDataForm.TYPE_FORM;
  }

  private _createFormGroup() {
    return new FormGroup({
      COLUMNA: new FormControl(null, Validators.required),
      ETIQUETA: new FormControl(null, Validators.required),
      IDENTIFICADOR: new FormControl(null, Validators.required),
      NOMBRE_CAMPO: new FormControl(null, Validators.required),
      VALOR_DEFECTO: new FormControl(null),
      PERMISOS: new FormControl([], Validators.required),
      DESHABILITAR: new FormControl(null),
      TAMANO_COLUMNA: new FormControl(12, Validators.required),
    });
  }
  
  async ngOnInit() {
    this.isLoading = true;
    await this._getUsers();
    this._getInformationComponent();
    this.isLoading = false;
  }

  private async _getUsers() {
    const USER: string = this.resourcesService.getUser();
    const LINE: number = this.resourcesService.getLineNumber();
    await lastValueFrom(this._usersProfilesService.getUsers(USER, LINE)).then(
      async (responseData: UsersResponse) => {
        if ( !responseData.error ) {
          this.arrUsers = [];
          for(const user of responseData.response){
            user.IDUSUARIO = await this._encService.decrypt(user.IDUSUARIO);
            this.arrUsers.push(user);
          }
          // this.arrUsers = responseData.response;
        } else {
          this.resourcesService.openSnackBar(`${ responseData.msg }`);
        }
      }, async (httpErrorResponse: HttpErrorResponse) => {
        let response = this.resourcesService.checkErrors(httpErrorResponse)
        if (response !== null && response.reload) {
          await this._getUsers();
        }
      }
    );
  }

  private async _getInformationComponent() {
    if (this.infoDataForm.COMPONENTS !== undefined) {
      const COMPONENTS: ComponentInformationCheckbox = this.infoDataForm.COMPONENTS;

      this.formGroup.controls['COLUMNA'].setValue(COMPONENTS.COLUMNA);
      if (this.infoDataForm.ENABLED) {
        this.formGroup.controls['COLUMNA'].enable();
      } else {
        this.formGroup.controls['COLUMNA'].disable();
      }
      this.formGroup.controls['ETIQUETA'].setValue(COMPONENTS.ETIQUETA);
      this.formGroup.controls['IDENTIFICADOR'].setValue(COMPONENTS.IDENTIFICADOR);
      this.formGroup.controls['NOMBRE_CAMPO'].setValue(COMPONENTS.NOMBRE_CAMPO);
      this.formGroup.controls['VALOR_DEFECTO'].setValue(COMPONENTS.VALOR_DEFECTO);
      let USER_PERMISSION: string[] = [];
      for (const userPermission of COMPONENTS.PERMISOS) {
        const USER: string = await this._encService.decrypt(userPermission);
        USER_PERMISSION.push(USER);
      }
      this.formGroup.controls['PERMISOS'].setValue(USER_PERMISSION);
      this.formGroup.controls['DESHABILITAR'].setValue(COMPONENTS.DESHABILITAR);
      this.formGroup.controls['TAMANO_COLUMNA'].setValue(COMPONENTS.TAMANO_COLUMNA);
    }
  }

  public updateColumnsNumber(accion: '+' | '-') {
    let columnNumber: number = this.formGroup.controls['TAMANO_COLUMNA'].value;
    if (accion === '+') {
      if (columnNumber < 12) {
        columnNumber += 1;
      }
    } else if (accion === '-') {
      if (columnNumber > 1) {
        columnNumber -= 1;
      }
    } else {
      this.resourcesService.openSnackBar(`Opción no disponible`);
      return;
    }
    this.formGroup.controls['TAMANO_COLUMNA'].setValue(columnNumber)
  }

  public allPermission() {
    const COUNT_USER: number = this.arrUsers.length;
    const USER_PERMISSION: string[] = this.formGroup.controls['PERMISOS'].value;
    const COUNT_PERMISSION: number = USER_PERMISSION.length;

    return COUNT_PERMISSION === COUNT_USER;
  }

  public somePermission() {
    const COUNT_USER: number = this.arrUsers.length;
    const USER_PERMISSION: string[] = this.formGroup.controls['PERMISOS'].value;
    const COUNT_PERMISSION: number = USER_PERMISSION.length;
    return COUNT_PERMISSION < COUNT_USER && COUNT_PERMISSION > 0;
  }

  public selectedAll(isChecked: boolean) {
    if (isChecked) {
      const USERS: string[] = this.arrUsers.map((user: UserResponse) => `${ user.IDUSUARIO }`);
      this.formGroup.controls['PERMISOS'].setValue(USERS);
    } else {
      this.formGroup.controls['PERMISOS'].setValue([]);
    }
  }

  public validateId() {
    const ID: string = this.formGroup.controls['IDENTIFICADOR'].value;
    if (this.arrIdentification.includes(ID)) {
      this.resourcesService.openSnackBar(`El identicador ya está registrado en otro componente.`);
      return false;
    }
    return true;
  }

  public async openExampleCheckbox() {
    const COMPONENT_CHECKBOX: ComponentInformationCheckbox = await this._createComponentCheckbox();
    this._dialog.open(ExampleComponentComponent, {
      data: {
        TYPE_COMPONENT: 'CHECKBOX',
        COMPONENT: COMPONENT_CHECKBOX
      },
      width: '450px',
    });
  }

  private async _createComponentCheckbox(): Promise<ComponentInformationCheckbox> {

    let columna = this.formGroup.controls['COLUMNA'].value;
    columna = columna.toString().trim();
    let etiqueta = this.formGroup.controls['ETIQUETA'].value;
    etiqueta = etiqueta.toString().trim();
    let identificador = this.formGroup.controls['IDENTIFICADOR'].value;
    identificador = identificador.toString().trim();
    let nombreCampo = this.formGroup.controls['NOMBRE_CAMPO'].value;
    nombreCampo = nombreCampo.toString().trim();
    let valorDefecto = this.formGroup.controls['VALOR_DEFECTO'].value;
    let permisos = this.formGroup.controls['PERMISOS'].value;
    let PERMISOS_ENC: string[] = [];
    permisos.forEach(async (user: string) => {
      const ENC_USER: string = await this._encService.encrypt(user);
      PERMISOS_ENC.push(ENC_USER);
    });

    let deshabilitar = this.formGroup.controls['DESHABILITAR'].value;
    let tamanoColumna = this.formGroup.controls['TAMANO_COLUMNA'].value;

    const COMPONENT_CHECKBOX: ComponentInformationCheckbox = {
      COLUMNA: columna,
      ETIQUETA: etiqueta,
      IDENTIFICADOR: identificador,
      NOMBRE_CAMPO: nombreCampo,
      VALOR_DEFECTO: valorDefecto,
      PERMISOS: PERMISOS_ENC,
      DESHABILITAR: deshabilitar,
      TAMANO_COLUMNA: tamanoColumna,
    }

    return COMPONENT_CHECKBOX;
  }
  
  public async saveComponent() {
    this._dialog.open(AlertComponent, {
      data: {
        title: 'Confirmación',
        description: '¿Está seguro de registrar el componente CHECKBOX?',
        icon: 'warning',
      },
      disableClose: true,
    }).afterClosed().subscribe(async (response) => {
      if (response) {
        const COMPONENT_CHECKBOX: ComponentInformationCheckbox = await this._createComponentCheckbox();
        this._dialogRef.close(COMPONENT_CHECKBOX);
      }
    });
  }
}
