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

import { RequestError } from './requesterror';

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

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

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

    constructor(private http: HttpClient) {
    }

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

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

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

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

}
