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, SERVER_API_URL_COMS} 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_COMS + '/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.$localStorage.clear('moduleId');
            this.$localStorage.clear('userInfo');
            this.$sessionStorage.clear('accessToken');
            observer.complete();
        });
    }
}
