import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
import {Router} from "@angular/router";

import {environment} from '@environments/environment';
import {OauthToken, User} from '@app/_models';

@Injectable({providedIn: 'root'})
export class AuthenticationService {
  public token: BehaviorSubject<OauthToken>;
  public user: BehaviorSubject<User>;

  constructor(private http: HttpClient, private router: Router) {
    this.token = new BehaviorSubject<OauthToken>(JSON.parse(localStorage.getItem('oauthToken')));
    this.user = new BehaviorSubject<any>(null);
  }

  get oauthTokenValue() {
    return this.token.value;
  }

  public get privileges() {
    return this.user.value?.privileges;
  }
  get isAdmin() {
    return this.privileges?.admin;
  }
  get isExpert() {
    return this.privileges?.expert;
  }
  get isMainCompanyMember() {
    return this.privileges?.mainCompanyMember;
  }



  signup(data: any): Observable<any> {
    return this.http.post(`${environment.apiUrl}/api/signup`, data);
  }

  getToken(username: string, password: string): Observable<any> {
    let data = {grant_type: 'password', client_id: environment.clientId, client_secret: environment.clientSecret, username: username, password: password};
    return this.http.post(`${environment.apiUrl}/oauth/token`, data);
  }
  saveToken(token: OauthToken) {
    localStorage.setItem('oauthToken', JSON.stringify(token));
    this.token.next(token);
    this.checkUser();
  }

  checkUser(params?: any) {
    if (this.token.value) {
      if (!params) params = {include: 'avatar,privileges'};
      this.http.get(`${environment.apiUrl}/api/me`, {params: params}).subscribe((res: any) => {
        this.user.next(res?.data);
      });
    }
  }


  logout() {
    localStorage.removeItem('oauthToken');
    this.token.next(null);
    this.user.next(null);
  }


  forget(email: string): Observable<any> {
    return this.http.post(`${environment.apiUrl}/api/passwords/reset`, {email});
  }

  restore(data: any): Observable<any> {
    return this.http.put(`${environment.apiUrl}/api/passwords/reset`, data);
  }

  popup(path: any) {
    this.router.navigate([ {outlets: {auth: path}}], {skipLocationChange: true}).then();
  }
}
