import { Component, OnInit } from '@angular/core';
import { PermissionsInterface } from '../../../../interfaces/permissions.interface';
import { ExportableSpreadsheetsListItem, ExportableSpreadsheetsListResponse, ModuleSpreadsheetsListItem, ProfileExportPermissionsListItem, ProfileExportPermissionsListResponse } from '../../../../interfaces/control-panel.interface';
import { ActivatedRoute } from '@angular/router';
import { ResourcesService } from '../../../../services/resources.service';
import { UsersProfilesService } from '../../../../services/users-profiles.service';
import { EncService } from '../../../../services/enc.service';
import { ControlPanelService } from '../../../../services/control-panel.service';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../../interfaces/profile.interface';

@Component({
    selector: 'app-data-election-config',
    templateUrl: './data-election-config.component.html',
    styleUrl: './data-election-config.component.css',
    standalone: false
})
export class DataElectionConfigComponent implements OnInit {
  screenSize: number;
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  idProfile: string;

  permissions: PermissionsInterface[];
  exportPermissions: Map<string, boolean>;
  profileExportPermissions: ProfileExportPermissionsListItem[];
  exportableSpreadsheets: ModuleSpreadsheetsListItem[];

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _resourcesService: ResourcesService,
    private _usersProfilesService: UsersProfilesService,
    private _encService: EncService,
    private _controlPanelService: ControlPanelService,
  ) {
    this.screenSize = window.innerWidth;
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.idProfile = '';

    this.permissions = [];
    this.exportPermissions = new Map();
    this.profileExportPermissions = [];
    this.exportableSpreadsheets = [];
  }

  ngOnInit(): void {
    this._activatedRoute.queryParams.subscribe(params => {
      let idProfile = params['data'];
      if(idProfile == undefined){
        this._resourcesService.openSnackBar('No se envió información.');
        this.goBack(1);
      }else{
        this.idProfile = idProfile;
        this.getProfileExportPermissions(idProfile);
      }
    });
  }

  goBack(steps: number){
    window.history.go(steps * -1);
  }

  async getProfileExportPermissions(idProfile: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let profilePermissions: ProfileExportPermissionsListResponse = await lastValueFrom(this._controlPanelService.getProfileExportPermissions(
        idProfile,
        idUser,
        1
      ));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let profilePermissionsArr: ProfileExportPermissionsListItem[] = [];
        for(const permission of profilePermissions.response){
          permission.id = await this._encService.decrypt(permission.id);
          profilePermissionsArr.push(permission);
        }

        this.profileExportPermissions = profilePermissionsArr;
        this.getExportableSpreadsheets(idProfile);
      }
    }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 getExportableSpreadsheets(idProfile: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let exportableSpreadsheets: ExportableSpreadsheetsListResponse = await lastValueFrom(this._controlPanelService.getExportableSpreadsheets(idUser, 1));

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

      if(this.hasError){
        this.isLoading = false;
      }else{
        let moduleSpreadsheets: ModuleSpreadsheetsListItem[] = [];
        for(const module of exportableSpreadsheets.response){
          module.module = await this._encService.decrypt(module.module);
          for(const spreadsheet of module.spreadsheets){
            spreadsheet.id = await this._encService.decrypt(spreadsheet.id);
            spreadsheet.name = await this._encService.decrypt(spreadsheet.name);

            let spreadsheetPermission = this.profileExportPermissions.filter(item => item.id == spreadsheet.id);
            if(spreadsheetPermission.length > 0){
              this.exportPermissions.set(spreadsheet.id, spreadsheetPermission[0].value);
            }else{
              this.exportPermissions.set(spreadsheet.id, false);
            }
          }

          moduleSpreadsheets.push(module);

          let modulePermission = this.profileExportPermissions.filter(item => item.id == module.module);
          if(modulePermission.length > 0){
            this.exportPermissions.set(module.module, modulePermission[0].value);
          }else{
            this.exportPermissions.set(module.module, false);
          }
        }

        this.exportableSpreadsheets = moduleSpreadsheets;
        this.getProfile(idProfile);
      }
    }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 getProfile(idProfile: string){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let profile: ProfileInterface = await lastValueFrom(this._usersProfilesService.getProfile(idProfile, idUser, 1));

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

      if(!this.hasError){
        let permissionsArr: PermissionsInterface[] = [];
        for(const permission of profile.response.PERMISOS.permissions){
          permission.id = await this._encService.decrypt(permission.id);

          let moduleFilt = this.exportableSpreadsheets.filter(item => item.module == permission.id);
          if(moduleFilt.length > 0){
            moduleFilt[0].moduleName = `${moduleFilt[0].module} - ${permission.name}`;
          }
        }

        this.permissions = permissionsArr;
      }

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

  onResize():void{
    this.screenSize = window.innerWidth;
  }

  permissionsChange(event: any, id: string, spreadsheets: ExportableSpreadsheetsListItem[] | undefined){
    let idStr = '';
    if(id.includes(' - ')){
      let idArr = id.split(' - ');
      idStr = idArr[0].trim();
    }else{
      idStr = id;
    }
    
    this.exportPermissions.set(idStr, event.checked);
    if(spreadsheets != undefined){
      this.changeChildrenCheckStatus(spreadsheets, event.checked);
    }
  }

  private changeChildrenCheckStatus(children: ExportableSpreadsheetsListItem[], status: boolean){
    for(const child of children){
      this.exportPermissions.set(child.id, status);
    }
  }

  async saveExportPermissions(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let profileExportPermissionsObj: any = {};

      for(const [key, value] of this.exportPermissions){
        profileExportPermissionsObj[key.trim()] = value;
      }

      let profileExportPermissionsStr = JSON.stringify(profileExportPermissionsObj);
      let profileExportPermissionsEnc = await this._encService.encrypt(profileExportPermissionsStr);
      let formData = new FormData();

      formData.append('id_user', idUser);
      formData.append('linea', '1');
      formData.append('permissions', profileExportPermissionsEnc);
      formData.append('id_profile', this.idProfile);

      await lastValueFrom(this._controlPanelService.saveProfileExportPermissions(formData));

      this._resourcesService.openSnackBar('Los permisos se actualizaron correctamente.');
      this.goBack(1);
    }catch(error: any){
      if(error.error == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else if(error.error.msg == undefined){
        this._resourcesService.openSnackBar('Ocurrió un error inesperado.');
      }else{
        this._resourcesService.openSnackBar(error.error.msg);
      }
    }
  }
}
