import { Injectable }                               from '@angular/core'
import { HttpClient }                               from '@angular/common/http'
import { Router } from '@angular/router'

import { HelperService }                            from '@k-services/svc.helper'

import 'rxjs/add/operator/toPromise';
import { ReplaySubject } from 'rxjs';
import { finalize, tap } from 'rxjs/operators';
import { BasketService } from '@k-core/services/svc.basket';
import { LocalstorageService } from '@k-core/services/general/storage';

interface User {
    id: number;
    email: string;
    key: string;
    password?: string;
    user_group?: string;
}

interface UserType {
    status: boolean;
    data: {
        state: boolean;
        message: string;
        userData: {
            token: string;
            userGroup: string;
        }
    }
}


@Injectable()
export class UserService {


    

    // Observables
    checkUserSource = new ReplaySubject<boolean>()
    checkUser$ = this.checkUserSource.asObservable()

    constructor(
        public localStorage: LocalstorageService,
        private basket: BasketService,
        private _helper: HelperService,
        private http: HttpClient,
        private _router: Router
    ) { }

    login: string = this._helper.server + 'feed/set/customer'
    checkUser: string = this._helper.server + 'feed/get/customer'

    checkLogin() {

        this.http.get(this.checkUser + this._helper.key + '&noCache').toPromise().then((response: any) => {

            this.checkUserSource.next(response.data.state)

            if(response.data.state) {
                this.constructUser(response.data)
            } else {
                this.logout()
            }
        })
    }


    /**
     * Constructs the user, putting everything in it's right place
     */
    constructUser(data) {

        // Gets users token and group
        let userKey = data.userData.token
        let userGroup = data.userData.userGroup

        // Stores users token and group in localStorage
        this.localStorage.setItem('user-key', userKey)
        this.localStorage.setItem('user-group', userGroup)

        // this._router.navigate(['/'])
    }

    /**
     * Sends a request to API, to check if username and password is correct
     * Gets key and user group back, key is a generated value, that will be parsed
     * with several other messages sent, to ensure, that requests are based on matching
     * the user and user_group
     * 
     * @param {Object} - loginAttempt Sends Email + Password to service
     * @returns {void} - TODO: Add a clarification if user has been logged in or not
     */
    verify(loginAttempt): Promise<any> {

        let object = {
            email: loginAttempt.email,
            password: loginAttempt.password,
            key: this._helper.apiKey,
            websiteId: this._helper.websiteId,
            storeId: this._helper.storeId,
            noCache: true
        }


        return this.http.post(this.login, object).toPromise().then((response: any) => {

            let user = response
            let result;


            if(!user.data.state) {

                // Returns error message to caller
                result = user.data.message

            } else {

                this.constructUser(user.data)
                result = 'success'

                if(user.data.hasOwnProperty('redirectUrl')) {
                    window.location.href = user.data.redirectUrl
                }

            }

            return result
        })
    }


    /**
     * Clears localStorage variables, and logs user out, effectively.
     */
    logout() {

        let object = {
            logout: true,
            key: this._helper.apiKey,
            storeId: this._helper.storeId,
            websiteId: this._helper.websiteId
        }

        this.http.post(this.login, object).toPromise().then(response => {
            
            this.localStorage.removeItem('user-key')
            this.localStorage.removeItem('user-group')

            this._router.navigate(['/'])
        })
    }

    logoutAsSubscribe() {
        let object = {
            logout: true,
            key: this._helper.apiKey,
            storeId: this._helper.storeId,
            websiteId: this._helper.websiteId,
            noCache: true
        }

        return this.http.post(this.login, object)
            .pipe(
                tap(() => {

                    this.basket.emptyBasket()
                    this.localStorage.removeItem('user-key')
                    this.localStorage.removeItem('user-group')

                    this._router.navigate(['/'])
                })
            )
    }
}



