import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
import { environment } from '../../environments/environment';

@Injectable()
export class AuthenticationService {
    // Public
    public currentClient: any;
    public user: string;

    // Private
    private redirectUrl: string;
    private token: any;
    private clients: any;
    private userData: any;
    private _currentClient = new Subject<object>();

    currentClient$ = this._currentClient.asObservable();

    constructor(private http: HttpClient) { }

    login(email: string, password: string) {
        this.user = email;
        return this.http.post<any>(environment.apiUrl + 'auth/login', { email: email, password: password })
            .map(response => {
                if (response.message === 'token_generated') {
                    this.token = response.data.token;
                    let role = response.data.role;
                    localStorage.setItem('token', this.token);
                    localStorage.setItem('user', this.user);
                    localStorage.setItem('role', role);
                }

                return response;
            });
    }

    logout() {
        // remove user from local storage to log user out
        localStorage.removeItem('token');
        localStorage.removeItem('role');
        return true;
    }

    isLoggedIn() {
        return !!localStorage.getItem('token');
    }

    setRedirectUrl(url: string) {
        this.redirectUrl = url;
    }

    getRedirectUrl() {
        return this.redirectUrl;
    }

    getToken() {
        return localStorage.getItem('token');
    }

    getClients() {
        return JSON.parse(localStorage.getItem('clientes'));
    }

    getCurrentClient() {
        if (!this.currentClient) {
            this.currentClient = JSON.parse(localStorage.getItem('clientes'))[0].NroCliente;
        }

        return this.currentClient;
    }

    setCurrentClient(currentClient) {
        this.currentClient = currentClient;
        this._currentClient.next(currentClient);
    }

    getUserData() {
        return JSON.parse(localStorage.getItem('userData'));
    }
}
