import {Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {catchError, map} from 'rxjs/operators';
import {Endpoints} from "./endpoints";
import { throwError} from "rxjs";
import {PasswordChangeRequest} from "../app.types";
import jwtDecode, {JwtPayload} from "jwt-decode";
import {Store} from "@ngxs/store";
import {LoginAction} from "../state/app.actions";
import {AppState} from "../state/app.state";

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  constructor(private http: HttpClient, private store: Store) {
    store.dispatch(new LoginAction(this.getToken()))
  }

  public getToken() {
    let currentUser = JSON.parse(localStorage.getItem('currentUser'));
    return currentUser?.token;
  }

  // login
  login(username: string, password: string) {
    return this.http.post<any>(Endpoints.POST_USERS_AUTHENTICATE(), {username: username, password: password})
      .pipe(
        // the backend service sends an instance of the user
        // user: any (because .post<any>)
        map(user => {
          // login successful if the response has jwt token
          if (user && user.token) {
            // store user details and jwt token in the local storage to keep the user logged in between page refreshes
            localStorage.setItem('currentUser', JSON.stringify(user));
            const decoded = jwtDecode<JwtPayload>(user.token);
            console.info("decoded", decoded);
            // this.user.next(user);
            this.store.dispatch(new LoginAction(user.token));
          }

          return user;
        }),
        catchError(err => {
          localStorage.removeItem('currentUser');
          this.store.dispatch(new LoginAction(null));
          return throwError(err);
        }),
      );
  }

  passwordChange(passwordChangeRequest: PasswordChangeRequest) {
    return this.http.post<any>(Endpoints.POST_USER_PASSWORD_CHANGE(), passwordChangeRequest)
  }

  // get  user() {
  //   return this._user;
  // }
  //
  public isLoggedIn() {
    return this.store.selectSnapshot(AppState.getToken);
  }

  // logout
  logout() {
    // remove user from local storage
    localStorage.removeItem('currentUser');
    this.store.dispatch(new LoginAction(null));
    // this.user.next(null);
  }
}
