import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders, HttpParams } from "@angular/common/http";

import { map } from "rxjs/operators";
import { Subject } from "rxjs";

import { FlashmessagesService } from "../flashmessages/flashmessages.service";

export interface token_answer {
    access_token: string,
    token_type: string
}

@Injectable()
export class AuthService {
    private access_token: string | null;

    private authenticationRequired = new Subject<boolean>();
    onAuthenticationRequired$ = this.authenticationRequired.asObservable();

    is_authenticated = false;
    private isAuthenticated = new Subject<boolean>();
    onIsAuthenticated$ = this.isAuthenticated.asObservable();

    constructor(private http: HttpClient,
                private flashMessage: FlashmessagesService) {
        this.access_token = localStorage.getItem('authtoken')
        this.is_authenticated = Boolean(this.access_token)
        this.isAuthenticated.next(this.is_authenticated)
    }

    login(username:string, password:string ) {
        const body = new HttpParams()
            .set('username', username)
            .set('password', password);

        return this.http.post<token_answer>('/api/v1/auth/login', body.toString(),
            {
                headers: new HttpHeaders()
                .set('Content-Type', 'application/x-www-form-urlencoded')
            }).pipe(map( v => {
                localStorage.setItem('authtoken', v.access_token);
                this.access_token = v.access_token
                this.flashMessage.success('Login successful. Welcome ' + username);
                this.is_authenticated = true;
                this.isAuthenticated.next(this.is_authenticated)
                return username
            } ));
    }

    logout() {
        return this.http.post<token_answer>('/api/v1/auth/logout', '',
            {
                headers: new HttpHeaders()
            }).pipe(map( v => {
                localStorage.removeItem('authtoken');
                this.access_token = null;
                this.flashMessage.success('Logout successful. Goodbye');
                this.is_authenticated = false;
                this.isAuthenticated.next(this.is_authenticated)
            } ));
    }

    getAuthorizationToken() {
        return `Bearer ${this.access_token}`;
    }

    requestAuth() {
        localStorage.removeItem('authtoken');
        this.access_token = null;
        this.authenticationRequired.next(true);
        this.is_authenticated = false;
        this.isAuthenticated.next(this.is_authenticated)
    }
}