import ngModule from '../../module';
import Component from 'core/lib/component';
import './style.scss';

class Controller extends Component {
    set roadmap(value) {
        this._roadmap = value;
        this.$.summary = null;
        if (!value) return;

        this.loadData();
    }

    get roadmap() {
        return this._roadmap;
    }

    loadData() {
        const filter = {
            include: [
                {relation: 'supplier'},
                {relation: 'worker'},
                {relation: 'expeditionTruck',
                    scope: {
                        include: [
                            {relation: 'warehouse'}
                        ]
                    }}
            ]
        };
        this.$http.get(`Roadmaps/${this.roadmap.id}`, {filter})
            .then(res => this.$.summary = res.data);
    }

    getETD() {
        const eta = new Date(this.roadmap.etd);
        eta.setDate(eta.getDate() + 1);

        this.expeditionTruck = {eta: eta};
    }

    onAddAccept() {
        try {
            const data = {
                roadmapFk: this.roadmap.id,
                warehouseFk: this.expeditionTruck.warehouseFk,
                eta: this.expeditionTruck.eta,
                description: this.expeditionTruck.description
            };

            this.$http.post(`ExpeditionTrucks`, data)
                .then(() => {
                    this.loadData();
                    this.vnApp.showSuccess(this.$t('Data saved!'));
                });
        } catch (e) {
            this.vnApp.showError(this.$t(e.message));
        }
    }
}

ngModule.component('vnRoadmapSummary', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        roadmap: '<'
    }
});