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

class Controller extends Section {
    constructor($element, $scope, $anchorScroll, $location) {
        super($element, $scope);
        this.$anchorScroll = $anchorScroll;
        this.$location = $location;
        let today = Date.vnNew();
        today.setHours(0, 0, 0, 0);
        this.today = today.toJSON();
    }

    get item() {
        return this._item;
    }

    set item(value) {
        this._item = value;

        this.filter = {
            where: {itemFk: this.$params.id}
        };

        this.$.$applyAsync(() => {
            if (this.$params.warehouseFk)
                this.warehouseFk = this.$params.warehouseFk;
            else if (value)
                this.warehouseFk = this.vnConfig.warehouseFk;

            if (this.$params.lineFk)
                this.lineFk = this.$params.lineFk;
        });
    }

    set warehouseFk(value) {
        if (value && value != this._warehouseFk) {
            this._warehouseFk = value;
            this.card.warehouseFk = value;
            this.filter.where.warehouseFk = this.warehouseFk;

            this.$.model.refresh();
        }
    }

    get warehouseFk() {
        return this._warehouseFk;
    }

    set date(value) {
        this._date = value;
        this.filter.where.date = value;
        this.filter.where.warehouseFk = this.warehouseFk;

        this.$.model.refresh();
    }

    get date() {
        return this._date;
    }

    set showOld(value) {
        this._showOld = value;
        if (!this._showOld) this.date = null;
        else this.date = new Date();
    }

    get showOld() {
        return this._showOld;
    }

    scrollToLine(lineFk) {
        this.$.$applyAsync(() => {
            const hashFk = this.lineFk || lineFk;
            const hash = `vnItemDiary-${hashFk}`;
            this.$location.hash(hash);
            this.$anchorScroll();
        });
    }

    showDescriptor(event, sale) {
        let descriptor = 'entryDescriptor';
        if (sale.isTicket)
            descriptor = 'ticketDescriptor';

        this.$[descriptor].show(event.target, sale.origin);
    }

    $onDestroy() {
        if (this.$state.getCurrentPath()[2].state.name === 'item')
            this.card.reload();
    }
}

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

ngModule.vnComponent('vnItemDiary', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        item: '<'
    },
    require: {
        card: '?^vnItemCard'
    }
});