import { Injectable, Inject } from '@angular/core';
import { delay, map } from 'rxjs/operators';
import { apiAuthService } from './api/api.auth.service';
import { apiUserService } from './api/api.user.service';
import { User } from './model/user.interface';

import * as moment from 'moment';

import { of, EMPTY } from 'rxjs';

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

    constructor(
        private apiAuthService: apiAuthService,
        private apiUserService: apiUserService,
        @Inject('LOCALSTORAGE') private localStorage: Storage) {
    }

    login(email: string, password: string) {
        return this.apiAuthService.authenticate(email, password).
            pipe(map(response => {                
            // If the server returns a token, the login is successful
            if (response.token) {
                // Store user details and jwt token in local storage to keep user logged in between page refreshes
                this.localStorage.setItem('currentUser', JSON.stringify({
                    token: response.token,
                }));

                this.apiUserService.getCurrentUser().subscribe((user: User) => {
                    console.log(user);
                    const Storeduser = this.localStorage.getItem('currentUser');
                    if(Storeduser) {
                        const currentUser = JSON.parse(Storeduser);
                        currentUser.isAdmin = user.isAdmin;
                        currentUser.email = user.email;
                        currentUser.id = user._id;
                        currentUser.alias = user.email.split('@')[0];
                        currentUser.fullName = user.username;
                        currentUser.expiration = moment().add(30, 'days').toDate();
                        this.localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    }                    
                });
                return true;
            }
            return false;
        }));
    }

    logout(): void {
        // clear token remove user from local storage to log user out
        this.localStorage.removeItem('currentUser');
    }

    getCurrentUser(): any {
        // TODO: Enable after implementation
        const user = this.localStorage.getItem('currentUser');
        if (!user) {
            return null;
        }        
        return JSON.parse(user);
        // return {
        //     token: JSON.parse(user).token,
        //     isAdmin: true,
        //     email: 'john.doe@gmail.com',
        //     id: '12312323232',
        //     alias: 'john.doe@gmail.com'.split('@')[0],
        //     expiration: moment().add(1, 'days').toDate(),
        //     fullName: 'John Doe'
        // };
    }

    passwordResetRequest(email: string) {
        return of(true).pipe(delay(1000));
    }

    changePassword(email: string, currentPwd: string, newPwd: string) {
        return of(true).pipe(delay(1000));
    }

    passwordReset(email: string, token: string, password: string, confirmPassword: string): any {
        return of(true).pipe(delay(1000));
    }
}
