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

import {AppConfig} from '../config/app.config';
import {CartService} from './cart.service';

@Injectable()
export class AuthenticationService {
    constructor(private http: HttpClient,
                private cartService: CartService) {
    }

    login(username: string, password: string) {
        return this.http.post<any>(AppConfig.loginURL() + '&userid=' + username + '&password=' + password, {}, {headers: {'Content-Type': 'text/plain'}})
            .map(user => {
                // login successful if there's a jwt token in the response
                if (user && user.sessionID !== '') {
                    user.userName = username;
                    // store user details and jwt token in local storage to keep user logged in between page refreshes
                    sessionStorage.setItem(AppConfig.relativeURL + 'currentUser', JSON.stringify(user));
                    this.getUserData(user).subscribe(
                        data => {
                            const userData = data.dataset.ttGetUserDetails[0];
                            sessionStorage.setItem(AppConfig.relativeURL + 'userData', JSON.stringify(userData));
                            this.cartService.createCart(user.sessionID, userData.id_cust)
                                .subscribe(
                                    cartData => {
                                        sessionStorage.setItem(AppConfig.relativeURL + 'cartData', JSON.stringify(cartData));
                                        this.cartService.updateCartItems(user, cartData.sessionID);
                                    },
                                    error => {
                                        console.log(error);
                                    });
                            this.getPriceOptions(user, username).subscribe(
                                priceViewOptionsData => {
                                    const priceViewOptions = priceViewOptionsData.dataset.PriceViewOptions[0];
                                    sessionStorage.setItem(AppConfig.relativeURL + 'priceViewOptions', JSON.stringify(priceViewOptions));
                                });
                        },
                        error => {
                            console.log(error);
                        });
                } else {
                    throw (user.msg);
                }

                return user;
            });
    }

    getUserData(user) {
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.getUserDetails + user.sessionID, {
            'userName': user.userName,
            'companyID': 1,
            'tpa': 'tportal'
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

    getPriceOptions(user, username) {
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.getPriceViewOptionsTP + user.sessionID, {
            'deviceID': 'tportal',
            'tradePortalUser': username
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

    logout() {
        // remove user from local storage to log user out
        sessionStorage.removeItem(AppConfig.relativeURL + 'currentUser');
    }
}
