import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {AppConfig} from '../config/app.config';
import {HttpClient} from '@angular/common/http';
import {MatTableDataSource} from '@angular/material';

@Injectable()
export class CartService {
    private cartItems = new BehaviorSubject<number>(0);
    cartCount = this.cartItems.asObservable();
    cartData: any;
    currentUser: any;
    userData: any;

    constructor(private http: HttpClient) {
        this.loadData();
    }

    loadData() {
        this.currentUser = JSON.parse(sessionStorage.getItem(AppConfig.relativeURL + 'currentUser'));
        this.userData = JSON.parse(sessionStorage.getItem(AppConfig.relativeURL + 'userData'));
        this.cartData = JSON.parse(sessionStorage.getItem(AppConfig.relativeURL + 'cartData'));
    }

    createCart(sessionID: string, customerID: string) {
        this.loadData();
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.createCart + sessionID, {
            'deviceID': 'tportal',
            'sessionType': 'type',
            'customerID': customerID
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

    deleteCart(sessionID: string, cartSessionID: string) {
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.deleteCart + sessionID, {
            'sessionID': cartSessionID
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

    getCart(currentUser, cartSessionID: string) {
        this.loadData();
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.getCartContents + currentUser.sessionID, {
            'userName': currentUser.userName,
            'sessionID': cartSessionID,
            'tpaID': 'tportal'
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

    updateCartItems(currentUser, cartSessionID) {
        this.loadData();
        this.getCart(currentUser, cartSessionID).subscribe(
            data => {
                this.cartItems.next(data.dataset.CartContents.length);
            },
            error => {
                console.log(error); // Error if any
            });
    }

    addItem(currentUser, cartSessionID, product, quantity: number, unitSell: number) {
        this.loadData();
        quantity = +quantity;
        product.quantity = quantity;
        product.id = product.productID;
        this.addProduct(currentUser.sessionID, cartSessionID, product, quantity, unitSell).subscribe(
            data => {
                this.updateCartItems(currentUser, cartSessionID);
            },
            error => {
                console.log(error); // Error if any
            });
    }

    removeItem(currentUser, cartSessionID, product) {
        this.loadData();
        this.deleteProduct(currentUser.sessionID, cartSessionID, product).subscribe(
            data => {
                this.updateCartItems(currentUser, cartSessionID);
            },
            error => {
                console.log(error); // Error if any
            });
    }

    updateItem(currentUser, cartSessionID, product) {
        this.loadData();
        this.updateProduct(currentUser.sessionID, cartSessionID, product).subscribe(
            data => {
                this.updateCartItems(currentUser, cartSessionID);
            },
            error => {
                console.log(error); // Error if any
            });
    }


    private updateProduct(sessionID, cartSessionID, product) {
        this.loadData();
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.updateCartProduct + sessionID, {
            'sessionID': cartSessionID,
            'lineID': product.lineID,
            'roomTypeID': '',
            'productID': product.productID,
            'quoteQty': product.prodQty,
            'UOM': product.UOM,
            'customerID': this.userData.id_cust,
            'unitSell': 0,
            'quoteComments': ''
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

    private addProduct(sessionID, cartSessionID, product, quantity: number, unitSell: number) {
        this.loadData();
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.addCartProduct + sessionID, {
            'sessionID': cartSessionID,
            'roomTypeID': '',
            'productID': product.productID,
            'quoteQty': quantity,
            'UOM': 'EA',
            'customerID': this.userData.id_cust,
            'unitSell': unitSell,
            'quoteComments': ''
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

    private deleteProduct(sessionID, cartSessionID, product) {
        this.loadData();
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.deleteCartProduct + sessionID, {
            'sessionID': cartSessionID,
            'productID': product.productID,
            'lineID': product.lineID
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }
}
