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

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

export class ProductsComponent implements OnInit {
    displayedColumns = ['productLongDesc', 'prodQty', 'add'];
    dataSource;
    currentUser: any;
    cartData: any;
    products = [];
    prodQty = 1;
    searchStr;
    showSearch = false;

    constructor(private route: ActivatedRoute,
                private router: Router,
                private http: HttpClient,
                private cartService: CartService) {
        this.currentUser = JSON.parse(sessionStorage.getItem(AppConfig.relativeURL + 'currentUser'));
        this.cartData = JSON.parse(sessionStorage.getItem(AppConfig.relativeURL + 'cartData'));
    }


    ngOnInit() {
        this.route.params.subscribe(params => {
            if (params.prodCategory && params.prodType && params.prodClass) {
                this.getProducts(this.currentUser, params).subscribe(
                    data => {
                        if (data.dataset) {
                            PRODUCT_DATA = data.dataset.getProductsByType[0].productGallery;
                            PRODUCT_DATA.forEach(eachObj => {
                                eachObj.prodQty = 1;
                            });
                            this.dataSource = new MatTableDataSource(PRODUCT_DATA);
                        }
                    },
                    error => {
                        console.log(error); // Error if any
                    });
            } else if (params.searchStr) {
                this.searchProducts(this.currentUser, params.searchStr).subscribe(
                    data => {
                        if (data.dataset) {
                            PRODUCT_DATA = data.dataset.ProductList;
                            PRODUCT_DATA.forEach(eachObj => {
                                eachObj.prodQty = 1;
                            });
                            this.dataSource = new MatTableDataSource(PRODUCT_DATA);
                        }
                    },
                    error => {
                        console.log(error); // Error if any
                    });
            }
        });
    }

    search(searchStr) {
        const item = {};
        (<any>item).searchStr = searchStr;
        this.router.navigate([AppConfig.routes.products, item]);
    }

    increment(product) {
        if (isNaN(product.prodQty)) {
            product.prodQty = 1;
        }
        product.prodQty++;
    }

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

    order(product) {
        this.cartService.addItem(this.currentUser, this.cartData.sessionID, product, product.prodQty, 0);
    }

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

    private getProducts(currentUser, params) {
        this.showSearch = false;
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.getProductsByCategoryTP + currentUser.sessionID, {
            'userName': currentUser.userName,
            'deviceID': 'tportal',
            'templateID': 0,
            'searchCategory': params.prodCategory,
            'searchType': params.prodType,
            'searchClass': params.prodClass,
            'searchString': '',
            'productIDString': '',
            'inStockOnly': false,
            'incGST': false,
            'page': 1,
            'pagesize': 10000,
            'lineID': 1
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

    private searchProducts(currentUser, searchStr: string) {
        this.showSearch = true;
        this.searchStr = searchStr;
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.searchProductTP + currentUser.sessionID, {
            'userName': currentUser.userName,
            'deviceID': 'tportal',
            'idString': '',
            'descString': searchStr,
            'incGST': true
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

}

export interface Product {
    productID: string;
    productLongDesc: string;
    prodQty: number;
}

let PRODUCT_DATA: Product[];
