import { Component, OnInit } from '@angular/core';
import { ExportableSpreadsheetsListResponse, ProfileExportPermissionsListItem, ProfileExportPermissionsListResponse } from '../../../interfaces/control-panel.interface';
import { FormControl, FormGroup } from '@angular/forms';
import { MatTableDataSource } from '@angular/material/table';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { ControlPanelService } from '../../../services/control-panel.service';
import { EncService } from '../../../services/enc.service';
import { UsersProfilesService } from '../../../services/users-profiles.service';
import { ResourcesService } from '../../../services/resources.service';
import { lastValueFrom } from 'rxjs';
import { ProfileInterface } from '../../../interfaces/profile.interface';

interface ExportablePermission {
  id: string;
  name: string;
  disabled: boolean;
}
@Component({
    selector: 'app-spreadsheet-export',
    templateUrl: './spreadsheet-export.component.html',
    styleUrl: './spreadsheet-export.component.css',
    standalone: false
})
export class SpreadsheetExportComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;
  hasSearched: boolean;

  profileExportPermissions: ProfileExportPermissionsListItem[];
  modulesPermissions: ExportablePermission[];
  spreadsheetsPermissions: Map<string, ExportablePermission[]>;

  range = new FormGroup({
    start: new FormControl<Date | null>({value: null, disabled: true}),
    end: new FormControl<Date | null>({value: null, disabled: true}),
  });

  moduleControl: FormControl;
  reportControl: FormControl;

  dataSource: MatTableDataSource<any>;

  constructor(
    private _matIconRegistry: MatIconRegistry,
    private _domSanitizer: DomSanitizer,
    private _controlPanelService: ControlPanelService,
    private _encService: EncService,
    private _usersProfilesService: UsersProfilesService,
    private _resourcesService: ResourcesService,
  ) {
    this._matIconRegistry.addSvgIcon(
      'xls',
      this._domSanitizer.bypassSecurityTrustResourceUrl(window.location.origin + "/assets/img/custom_icons/xls.svg")
    );

    this.isLoading = true;
    this.hasError = false;
    this.errorStr = '';
    this.hasSearched = false;

    this.profileExportPermissions = [];
    this.modulesPermissions = [];
    this.spreadsheetsPermissions = new Map();

    this.moduleControl = new FormControl<string | null>({value: null, disabled: true});
    this.reportControl = new FormControl<string | null>({value: null, disabled: true});

    this.dataSource = new MatTableDataSource();
  }

  ngOnInit(): void {
    this.getProfilePermissions();
  }

  async getProfilePermissions(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let profile = localStorage.getItem('perfil')!;
      let permissions: ProfileExportPermissionsListResponse = await lastValueFrom(this._controlPanelService.getProfileExportPermissions(profile, idUser, 1));

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

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

        this.profileExportPermissions = profilePermissionsArr;
        this.getExportableSpreadsheets();
      }
    }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(){
    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 moduleAccessArr: ExportablePermission[] = [];
        for(const module of exportableSpreadsheets.response){
          module.module = await this._encService.decrypt(module.module);

          let spreadsheetsAccessArr: ExportablePermission[] = [];
          for(const spreadsheet of module.spreadsheets){
            let idSpreadsheetDec = await this._encService.decrypt(spreadsheet.id);
            let spreadsheetNameDec = await this._encService.decrypt(spreadsheet.name);
            let permissionFilt = this.profileExportPermissions.filter(item => item.id == idSpreadsheetDec);
            let spreadsheetObj: ExportablePermission = {
              id: spreadsheet.id,
              name: `${idSpreadsheetDec} - ${spreadsheetNameDec}`,
              disabled: permissionFilt.length > 0 ? !permissionFilt[0].value : true,
            };

            spreadsheetsAccessArr.push(spreadsheetObj);
          }

          let moduleFilt = this.profileExportPermissions.filter(item => item.id == module.module);
          let moduleObj: ExportablePermission = {
            id: module.module,
            name: '',
            disabled: moduleFilt.length > 0 ? !moduleFilt[0].value : true,
          };

          moduleAccessArr.push(moduleObj);
          this.spreadsheetsPermissions.set(module.module, spreadsheetsAccessArr);
        }

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

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

      if(!this.hasError){
        for(const permission of profile.response.PERMISOS.permissions){
          let idModule = await this._encService.decrypt(permission.id);
          let moduleFilt = this.modulesPermissions.filter(item => item.id == idModule);
          if(moduleFilt.length > 0){
            moduleFilt[0].name = permission.name;
          }
        }
      }

      this.moduleControl.enable();
      this.range.controls.start.enable();
      this.range.controls.end.enable();

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

  public onResize():void {

  }

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

  moduleChange(value: string){
    this.reportControl.disable();
    this.reportControl.setValue(null);

    let moduleSpreadsheets = this.spreadsheetsPermissions.get(value);
    if(value != null && value != undefined && value != '' && moduleSpreadsheets!.length > 0){
      this.reportControl.enable();
    }
  }

  async exportData(){
    try{
      let moduleVal = this.moduleControl.value;
      if(moduleVal == null || moduleVal == undefined || moduleVal == ''){
        this._resourcesService.openSnackBar('Por favor seleccione un módulo antes de continuar');
        return;
      }else{
        moduleVal = await this._encService.encrypt(moduleVal);
      }

      let reportVal = this.reportControl.value;
      if(reportVal == null || reportVal == undefined || reportVal == ''){
        this._resourcesService.openSnackBar('Por favor seleccione un reporte antes de continuar');
        return;
      }

      let startDateStr = '-';
      if(this.range.controls.start.value != null){
        let startYear = this.range.controls.start.value.getFullYear();
        let startMonth = this.range.controls.start.value.getMonth();
        let startDay = this.range.controls.start.value.getDate();

        startDateStr = `${startYear}-${startMonth + 1}-${startDay}`;
      }

      let endDateStr = '-';
      if(this.range.controls.end.value != null){
        let endYear = this.range.controls.end.value.getFullYear();
        let endMonth = this.range.controls.end.value.getMonth();
        let endDay = this.range.controls.end.value.getDate();

        endDateStr = `${endYear}-${endMonth + 1}-${endDay}`;
      }

      let idUser = localStorage.getItem('idusuario')!;
      console.log(moduleVal);
      console.log(reportVal);
      console.log(startDateStr);
      console.log(endDateStr);
      console.log(idUser);
    }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);
      }
    }
  }
}
