import { Injectable } from '@angular/core';
import { BehaviorSubject, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { environment } from './../../environments/environment';

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

    auth: BehaviorSubject<any> = new BehaviorSubject(undefined);

    constructor(private http: HttpClient) {
    }

    getAuth() {
        return this.authMe().toPromise().then((data: any) => {
            this.auth.next(data);
            return data;
        }, error => {
            throw new Error(error);
        });
    }

    authMe() {
        return this.http.get(environment.apiUrl + "/auth/me");
    }

    login(loginModel) {
        return this.http.post(environment.apiUrl + "/auth/login", loginModel);
    }

    logout() {
        return this.http.post(environment.apiUrl + "/auth/logout", {});
    }

    passwordRequest(username) {
        const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
        return this.http.post(environment.apiUrl + "/auth/password/request", username, { headers, responseType: 'text' });
    }

    passwordReset(model) {
        const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
        return this.http.post(environment.apiUrl + "/auth/password/reset", model);
    }

    isTotpEnabled() {
        return this.http.get(environment.apiUrl + "/auth/totp");
    }

    createTotp() {
        return this.http.put(environment.apiUrl + "/auth/totp", {});
    }

    enableTotp(code) {
        return this.http.patch(environment.apiUrl + "/auth/totp", code);
    }

    removeTotp() {
        return this.http.delete(environment.apiUrl + "/auth/totp");
    }

    loginTotp(totpModel) {
        return this.http.post(environment.apiUrl + "/auth/login/totp", totpModel);
    }
}