import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';
import {MatTableDataSource} from '@angular/material';
import {HttpClient} from '@angular/common/http';
import {AppConfig} from '../config/app.config';
import {CartService} from '../core/cart.service';

@Component({
    templateUrl: 'list.component.html'
})

export class ListComponent implements OnInit {
    displayedColumns = ['prodDesc', 'prodQty', 'add'];
    dataSource;

    currentUser: any;
    userData: any;
    cartData: any;

    constructor(private route: ActivatedRoute,
                private router: Router,
                private http: HttpClient,
                private cartService: CartService) {

        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'));
    }

    ngOnInit() {
        this.route.params.subscribe(params => {
            this.getList(this.currentUser, params.id).subscribe(
                data => {
                    this.dataSource = new MatTableDataSource(data.dataset.CartContents);
                },
                error => {
                    console.log(error); // Error if any
                });
        });
    }

    increment(product) {
        product.prodQty++;
    }

    decrement(product) {
        if (product.prodQty <= 1) {
            return;
        }
        product.prodQty--;
    }

    openProduct(productID) {
        this.router.navigate([AppConfig.routes.product + '/' + productID]);
    }

    order(product) {
        this.getProduct(this.currentUser.sessionID, product.productID).subscribe(
            data => {
                if (undefined !== data.dataset) {
                    this.cartService.addItem(this.currentUser, this.cartData.sessionID, data.dataset.getProductDetails[0], product.prodQty, 0);
                }
            },
            error => {
                console.log(error); // Error if any
            });
    }

    private getProduct(sessionID: string, productID: string) {
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.getProductDetails + sessionID, {
            'deviceID': 'tportal',
            'productID': productID,
            'customerID': this.userData.id_cust,
            'incGST': true
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

    private getList(currentUser, cartSessionID: string) {
        return this.cartService.getCart(currentUser, cartSessionID);
    }
}

