import { Component, Inject, OnInit } from '@angular/core';
import { UserResponse, UsersResponse } from '../../../../interfaces/users.interface';
import { BroadcastListDetails, BroadcastListDetailsResponse, BroadcastListUsers } from '../../../../interfaces/control-panel.interface';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { EncService } from '../../../../services/enc.service';
import { ControlPanelService } from '../../../../services/control-panel.service';
import { lastValueFrom } from 'rxjs';

@Component({
    selector: 'app-broadcast-list-form',
    templateUrl: './broadcast-list-form.component.html',
    styleUrl: './broadcast-list-form.component.css',
    standalone: false
})
export class BroadcastListFormComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  isNew: boolean;
  action: string;
  users: UserResponse[];
  broadcastList: BroadcastListDetails | null;

  formGroup: FormGroup;

  constructor(
    @Inject(MAT_DIALOG_DATA) private _data: any,
    private _usersProfilesService: UsersProfilesService,
    private _encService: EncService,
    private _dialogRef: MatDialogRef<BroadcastListFormComponent>,
    private _controlPanelService: ControlPanelService,
  ) {
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';

    this.isNew = true;
    this.action = '';
    this.users = [];
    this.broadcastList = null;

    this.formGroup = new FormGroup({
      idBroadcastList: new FormControl({value: '', disabled: true}),
      broadcastListName: new FormControl('', [Validators.required, Validators.maxLength(75)]),
      broadcastListUsers: new FormControl([], [Validators.required, Validators.minLength(2)]),
    });
  }

  ngOnInit(): void {
    this.isNew = this._data.action == 'new';
    this.action = this.isNew ? 'Registrar' : 'Editar';

    if(this.isNew){
      this.getUsers();
    }else{
      this.getBroadcastList();
    }
  }

  async getBroadcastList(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let list: BroadcastListDetailsResponse = await lastValueFrom(this._controlPanelService.getBroadcastList(
        this._data.idList,
        idUser,
        1
      ));

      this.hasError = list.error;
      this.errorStr = list.msg;

      if(this.hasError){
        this.isLoading = false;
      }else{
        list.response.ID_LISTA = await this._encService.decrypt(list.response.ID_LISTA);
        list.response.INTEGRANTES_ARR = JSON.parse(list.response.INTEGRANTES) as BroadcastListUsers[];

        this.formGroup.controls['idBroadcastList'].setValue(list.response.ID_LISTA);
        this.formGroup.controls['broadcastListName'].setValue(list.response.NOMBRE_LISTA);

        this.broadcastList = list.response;
        this.getUsers();
      }
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async getUsers(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let users: UsersResponse = await lastValueFrom(this._usersProfilesService.getUsers(idUser, 1));

      this.hasError = users.error;
      this.errorStr = users.msg;

      if(!this.hasError){
        let usersArr: UserResponse[] = [];
        let currentUserDec = await this._encService.decrypt(idUser);
        let broadcastListUsers: string[] = [];

        if(this.broadcastList != null){
          for(const item of this.broadcastList.INTEGRANTES_ARR!){
            let idDec = await this._encService.decrypt(item.ID_USUARIO);
            broadcastListUsers.push(idDec);
          }
        }

        for(const user of users.response){
          let idUserDec = await this._encService.decrypt(user.IDUSUARIO);
          if(user.APEMAT != null){
            user.APEMAT = `${user.APEMAT} (${idUserDec})`;
          }else{
            user.APEPAT = `${user.APEPAT} (${idUserDec})`;
          }

          let userFilt = broadcastListUsers.filter(item => item == idUserDec);
          if(userFilt.length > 0){
            let broadcastListUsers = this.formGroup.controls['broadcastListUsers'].value;
            broadcastListUsers.push(user.IDUSUARIO);

            this.formGroup.controls['broadcastListUsers'].setValue(broadcastListUsers);
          }

          if(user.ESTATUS == 'Activo' && currentUserDec != idUserDec){
            usersArr.push(user);
          }
        }

        this.users = usersArr;
      }

      this.isLoading = false;
    }catch(error: any){
      if(error.error == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else if(error.error.msg == undefined){
        this.errorStr = 'Ocurrió un error inesperado.';
      }else{
        this.errorStr = error.error.msg;
      }

      this.hasError = true;
      this.isLoading = false;
    }
  }

  async saveList(){
    let formVal = this.formGroup.getRawValue();
    let formStr = JSON.stringify(formVal);
    let formEnc = await this._encService.encrypt(formStr);
    
    this._dialogRef.close(formEnc);
  }
}
