import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from "@angular/router";
import { Observable } from 'rxjs/Observable';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { SERVER_API_URL } from '../../app.constants';
import { EmitService } from "../../shared/event/eventEmitter";
@Injectable()
export class AuthServerProvider {
    constructor(
        private http: HttpClient,
        private router: Router,
        private $localStorage: LocalStorageService,
        private $sessionStorage: SessionStorageService,
        private emitService: EmitService
    ) {}

    getToken() {

        return this.$localStorage.retrieve('authenticationToken') || this.$sessionStorage.retrieve('authenticationToken');
    }

    login(credentials): Observable<any> {

        const data = {
            loginName: credentials.loginName,
            password: credentials.password,
            rememberMe: credentials.rememberMe
        };
        return this.http.post(SERVER_API_URL + '/login', data, {observe : 'response'}).map(authenticateSuccess.bind(this));
        function authenticateSuccess(resp) {
            const bearerToken = resp.body.data;
            if (bearerToken ) {
                this.$localStorage.store('accessToken', bearerToken);
                return true;
            }else{
                return false;
            }
        }
    }

    loginWithToken(jwt, rememberMe) {
        if (jwt) {
            this.storeAuthenticationToken(jwt, rememberMe);
            return Promise.resolve(jwt);
        } else {
            return Promise.reject('auth-jwt-service Promise reject'); // Put appropriate error message here
        }
    }

    storeAuthenticationToken(jwt, rememberMe) {
        if (rememberMe) {
            this.$localStorage.store('accessToken', jwt);
        } else {
            this.$sessionStorage.store('accessToken', jwt);
        }
    }

    logout(): Observable<any> {
        this.router.navigate(['app/login']);
        return new Observable((observer) => {
            this.$localStorage.clear('accessToken');
            this.$sessionStorage.clear('accessToken');
            observer.complete();
        });
    }
}
