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

@Component({
    templateUrl: 'product.component.html',
    styleUrls: ['product.component.scss']
})

export class ProductComponent implements OnInit {
    currentUser: any;
    userData: any;
    cartData: any;
    priceViewOptions: any;
    product: any = {};
    features: any = [];
    infos: any = [];
    cartItems: number;
    appConfig: IAppConfig = AppConfig;

    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'));
        this.priceViewOptions = JSON.parse(sessionStorage.getItem(AppConfig.relativeURL + 'priceViewOptions'));
    }


    ngOnInit() {
        this.cartService.cartCount.subscribe(res => this.cartItems = res);
        this.route.params.subscribe(params => {
            this.getProduct(this.currentUser.sessionID, params.id).subscribe(
                data => {
                    if (undefined !== data.dataset) {
                        this.product = data.dataset.getProductDetails[0];
                        this.product.prodQty = 1;
                    }
                },
                error => {
                    console.log(error); // Error if any
                });
            this.getFeaturesAndBenefits(this.currentUser.sessionID, params.id).subscribe(
                data => {
                    if (undefined !== data.dataset) {
                        this.features = data.dataset.getFeaturesAndBenefitsResponse;
                    }
                },
                error => {
                    console.log(error); // Error if any
                });
            this.getProductInformation(this.currentUser.sessionID, params.id).subscribe(
                data => {
                    if (undefined !== data.dataset) {
                        this.infos = data.dataset.getProductInformationResponse;
                    }
                },
                error => {
                    console.log(error); // Error if any
                });
        });
    }

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

    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 getFeaturesAndBenefits(sessionID: string, productID: string) {
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.getFeaturesAndBenefits + sessionID, {
            'deviceID': 'tportal',
            'productID': productID
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            return data;
        });
    }

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

    getImage(images) {
        if (undefined === images) {
            return;
        }
        const del = images.indexOf('|');
        const file = images.indexOf('S:');
        const last = images.lastIndexOf('http');
        const jpg = images.indexOf('.jpg');

        if (file !== -1 || images === '') {
            return 'noImage.gif';
        } else if (del === -1) {
            return images;
        } else if (jpg > del) {
            images = images.substr(last, jpg + 4);
            return images;
        } else {
            images = images.substr(0, jpg + 4);
            return images;
        }
    }

}

export interface Product {
    CFUOMList: string;
    Lead: string;
    RRP: number;
    UOMList: string;
    customerPrice: number;
    fileTypes: string;
    inStock: number;
    isTally: boolean;
    productFiles: string;
    productID: string;
    productLongDesc: string;
    productShortDesc: number;
}
