import ngModule from '../module';
import Section from 'salix/components/section';

class Controller extends Section {
    constructor($element, $) {
        super($element, $);

        const from = new Date();
        from.setDate(from.getDate() - 75);
        from.setHours(0, 0, 0, 0);

        const to = new Date();
        to.setDate(to.getDate() + 10);
        to.setHours(23, 59, 59, 59);

        this.filter = {
            where: {
                itemFk: this.$params.id,
                shipped: {
                    between: [from, to]
                }
            }
        };
        this._dateFrom = from;
        this._dateTo = to;
    }

    set dateFrom(value) {
        this._dateFrom = value;

        if (!value) return;

        const from = new Date(value);
        from.setHours(0, 0, 0, 0);

        const to = new Date(this._dateTo);
        to.setHours(23, 59, 59, 59);

        this.filter.where.shipped = {
            between: [from, to]
        };
        this.$.model.refresh();
    }

    set dateTo(value) {
        this._dateTo = value;

        if (!value) return;

        const from = new Date(this._dateFrom);
        from.setHours(0, 0, 0, 0);

        const to = new Date(value);
        to.setHours(23, 59, 59, 59);

        this.filter.where.shipped = {
            between: [from, to]
        };
        this.$.model.refresh();
    }

    get dateFrom() {
        return this._dateFrom;
    }

    get dateTo() {
        return this._dateTo;
    }

    exprBuilder(param, value) {
        switch (param) {
        case 'id':
        case 'quantity':
        case 'packageFk':
            return {[`b.${param}`]: value};
        case 'supplierFk':
            return {[`s.id`]: value};
        case 'warehouseFk':
            return {'tr.warehouseInFk': value};
        case 'landed':
            return {'tr.landed': {
                between: this.dateRange(value)}
            };
        }
    }

    dateRange(value) {
        const minHour = new Date(value);
        minHour.setHours(0, 0, 0, 0);
        const maxHour = new Date(value);
        maxHour.setHours(23, 59, 59, 59);

        return [minHour, maxHour];
    }
}

Controller.$inject = ['$element', '$scope'];

ngModule.vnComponent('vnItemLastEntries', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        item: '<'
    }
});