import ngModule from '../module';
import Popover from 'core/components/popover';
import './style.scss';

class Controller extends Popover {
    constructor(...args) {
        super(...args);
        this.totalBasquet = 0;
    }

    set prices(value) {
        this._prices = value;
        if (value && value[0].grouping)
            this.getTotalQuantity();
    }

    get prices() {
        return this._prices;
    }

    show(parent, item) {
        this.id = item.id;
        this.item = JSON.parse(JSON.stringify(item));
        this.maxQuantity = this.item.available;
        this.prices = this.item.prices;

        super.show(parent);
    }

    onClose() {
        this.id = null;
        this.item = {};
        this.tags = {};
        this._prices = {};
        this.totalQuantity = 0;
        super.onClose();
    }

    getTotalQuantity() {
        let total = 0;
        for (let price of this.prices) {
            if (!price.quantity) price.quantity = 0;
            total += price.quantity;
        }

        this.totalQuantity = total;
    }

    addQuantity(price) {
        this.getTotalQuantity();
        const quantity = this.totalQuantity + price.grouping;
        if (quantity <= this.maxQuantity)
            price.quantity += price.grouping;
    }

    getGroupings() {
        const filledRows = [];
        for (let priceOption of this.prices) {
            if (priceOption.quantity && priceOption.quantity > 0) {
                const priceMatch = filledRows.find(row => {
                    return row.warehouseFk == priceOption.warehouseFk
                        && row.price == priceOption.price;
                });

                if (!priceMatch)
                    filledRows.push(Object.assign({}, priceOption));
                else priceMatch.quantity += priceOption.quantity;
            }
        }

        return filledRows;
    }

    submit() {
        const filledRows = this.getGroupings();

        try {
            const hasInvalidGropings = filledRows.some(row =>
                row.quantity % row.grouping != 0
            );

            if (filledRows.length <= 0)
                throw new Error('First you must add some quantity');

            if (hasInvalidGropings)
                throw new Error(`The amounts doesn't match with the grouping`);

            const params = {
                orderFk: this.order.id,
                items: filledRows
            };
            this.$http.post(`OrderRows/addToOrder`, params)
                .then(() => {
                    this.vnApp.showSuccess(this.$t('Data saved!'));
                    this.hide();
                    if (this.card) this.card.reload();
                });
        } catch (e) {
            this.vnApp.showError(this.$t(e.message));
            return false;
        }
        return true;
    }
}

ngModule.vnComponent('vnOrderPricesPopover', {
    slotTemplate: require('./index.html'),
    controller: Controller,
    bindings: {
        order: '<'
    },
    require: {
        card: '?^vnOrderCard'
    }
});