import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { ResultApi } from 'src/app/models/result-api.model';
import { environment } from 'src/environments/environment';
import { AuthUser } from '../../models/auth.user.model';
import jwt_decode from 'jwt-decode';
import { ModuleSystem } from 'src/app/models/module.model';
import { PagesUser } from 'src/app/models/pages-user.model';
import { ActionsUser } from 'src/app/models/actions-user.model';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  private UserAuthenticate = false;
  public actionsUser: ActionsUser[];

  constructor(public httpClient: HttpClient,
              public router: Router) { }

  /*doRegister(value){
    return new Promise<any>((resolve, reject) => {
      this.afAuth.createUserWithEmailAndPassword(value.email, value.password)
      .then(res => {
        resolve(res);
      }, err => reject(err));
    });
  }

  doEmailAndPasswordLogin(value){
    return new Promise<any>((resolve, reject) => {
      this.afAuth
      .signInWithEmailAndPassword(value.email, value.password)
      .then(res => {
        console.log(res);
        resolve(res);
      }, err => reject(err));
    });
  } */

  login(value: AuthUser): Observable<ResultApi> {
    return this.httpClient.post<ResultApi>(`${environment.url}auth/login`, value);
  }

  logout() {
    localStorage.removeItem('user');
    localStorage.removeItem('token');
    this.router.navigate(['login']);
  }

  authenticate(value: AuthUser): Observable<ResultApi> {
    return this.httpClient.post<ResultApi>(`${environment.url}auth/authenticate`, value);
  }

  getDiscount(id: number = 0): Observable<ResultApi> {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    const token = this.getToken();
    const headers = new HttpHeaders().set('Authorization', `Basic ${token}`);
    let userId = user.id;
    if (id > 0){
      userId = id;
    }
    return this.httpClient.get<ResultApi>(`${environment.url}auth/discount-user/${userId}`);
  }

  getModules(id: number) {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    const token = this.getToken();
    const headers = new HttpHeaders().set('Authorization', `Basic ${token}`);
    let userId = user.id;
    if (id > 0){
      userId = id;
    }
    return this.httpClient.get<ModuleSystem[]>(`${environment.url}access-control/modules/${userId}`);
  }

  getPagesUser(moduleId: number) {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    const token = this.getToken();
    const headers = new HttpHeaders().set('Authorization', `Basic ${token}`);

    return this.httpClient.get<PagesUser[]>(`${environment.url}access-control/pages/${user.id}/${moduleId}`);
  }

  getActionsUser(moduleId: number) {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    const token = this.getToken();
    const headers = new HttpHeaders().set('Authorization', `Basic ${token}`);
    return this.httpClient.get<ActionsUser[]>(`${environment.url}access-control/actions/${user.id}/${moduleId}`);
  }

  setDataInLocalStorage(variableName: string, data: any) {
    localStorage.setItem(variableName, data);
  }

  getToken() {
    return localStorage.getItem('token');
  }

  getPayload() {
    try {
      return jwt_decode(this.getToken()) as any;
    } catch (Error) {
      return null;
    }
  }

  isManager() {
    const data = this.getPayload();
    console.log(JSON.stringify(data));
    return data.sectorId.toString() === data.sectorManagerId.toString();
  }

  getUserName() {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    return user.username;
  }

  getStoreName() {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    return user.name;
  }

  getUser() {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    return user.id;
  }

  getSeller() {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    return user.seller;
  }

  getSupervisor() {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    return user.supervisorId;
  }

  getStore() {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    return user.store;
  }

  getDeliveryTime() {
    const data = localStorage.getItem('user');
    const user = JSON.parse(data);
    return user.deliveryTime;
  }

  deleteDataLocalStorage(variableName: string) {
    localStorage.removeItem(variableName);
  }

  isAuthenticate(){
    console.log(localStorage.getItem('token'));
    return localStorage.getItem('token') != null;
  }

  userAction(processId: number, pageId: number, actionId: number) {
    const actionUser = this.actionsUser
        .find(action => action.moduleId == 2 &&
              action.processId == processId &&
              action.pageId == pageId &&
              action.actionId == actionId &&
              action.access == "S" );
    console.log(this.actionsUser);
    return actionUser !== undefined && actionUser!== null;
  }

}
