import ngModule from '../module';
import SearchPanel from 'core/components/searchbar/search-panel';
import './style.scss';

class Controller extends SearchPanel {
    constructor($, $element) {
        super($, $element);
        this.initFilter();
        this.fetchData();
    }

    $onChanges() {
        if (this.model)
            this.applyFilters();
    }

    fetchData() {
        this.$http.get('AgencyModes').then(res => {
            this.agencyModes = res.data;
        });
        this.$http.get('Warehouses').then(res => {
            this.warehouses = res.data;
        });
        this.$http.get('Continents').then(res => {
            this.continents = res.data;
        });
    }

    initFilter() {
        this.filter = {};
        if (this.$params.q) {
            this.filter = JSON.parse(this.$params.q);
            this.search = this.filter.search;
            this.totalEntries = this.filter.totalEntries;
        }
        if (!this.filter.scopeDays) this.filter.scopeDays = 7;
    }

    applyFilters(param) {
        if (typeof this.filter.scopeDays === 'number') {
            const shippedFrom = Date.vnNew();
            shippedFrom.setHours(0, 0, 0, 0);

            const shippedTo = new Date(shippedFrom.getTime());
            shippedTo.setDate(shippedTo.getDate() + this.filter.scopeDays);
            shippedTo.setHours(23, 59, 59, 999);
            Object.assign(this.filter, {shippedFrom, shippedTo});
        }

        this.model.applyFilter({}, this.filter)
            .then(() => {
                if (param && this.model._orgData.length === 1)
                    this.$state.go('travel.card.summary', {id: this.model._orgData[0].id});
                else
                    this.$state.go(this.$state.current.name, {q: JSON.stringify(this.filter)}, {location: 'replace'});
            });
    }

    removeParamFilter(param) {
        if (this[param]) delete this[param];
        delete this.filter[param];
        this.applyFilters();
    }

    onKeyPress($event, param) {
        if ($event.key === 'Enter') {
            this.filter[param] = this[param];
            this.applyFilters(param === 'search');
        }
    }
}

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