import { FunctionsService } from './../../../services/functions.service';
import { UserConsult, UserConsultResponse } from './../../../interfaces/user.interface';
import { lastValueFrom } from 'rxjs';
import { MatSnackBar } from '@angular/material/snack-bar';
import { EncService } from 'src/app/services/enc/enc.service';
import { UsersProfilesService } from 'src/app/services/users-profiles.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-my-profile',
  templateUrl: './my-profile.component.html',
  styleUrls: ['./my-profile.component.css']
})
export class MyProfileComponent implements OnInit {
  isLoading: boolean;
  hasError: boolean;
  errorStr: string;

  userInfo?: UserConsult;

  constructor(
    private _usersProfilesService: UsersProfilesService,
    private _encService: EncService,
    private _functService: FunctionsService,
  ) { 
    this.isLoading = true;
    this.hasError = false;
    this.errorStr = "";
  }

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

  async getMyProfile(){
    try{
      let idUser = localStorage.getItem('idusuario')!;
      let userInfo: UserConsultResponse = await lastValueFrom(this._usersProfilesService.getUser(idUser, idUser, 1));
      
      this.hasError = userInfo.error;
      this.errorStr = userInfo.msg;

      if(!this.hasError){
        this.userInfo = userInfo.response;
      }

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

  buildName(name: string, apePat: string, apeMat: string | null | undefined){
    return this._functService.buildName(name, apePat, apeMat);
  }
}
