import ngModule from '../module';

class Controller {
    constructor($scope, $http, $state, vnApp, $translate) {
        this.$scope = $scope;
        this.$http = $http;
        this.$state = $state;
        this.vnApp = vnApp;
        this.$translate = $translate;
    }

    set edit(value) {
        this._edit = value;
        this.clearDiscount();
        this.setNewDiscount();
    }

    get edit() {
        return this._edit;
    }

    set bulk(value) {
        this._bulk = value;
        this.setNewDiscount();
    }

    get bulk() {
        return this._bulk;
    }

    get newDiscount() {
        return this._newDiscount;
    }

    set newDiscount(value) {
        this._newDiscount = value;
        this.updateNewPrice();
    }

    updateNewPrice() {
        if (this.newDiscount && this.edit[0])
            this.newPrice = (this.edit[0].quantity * this.edit[0].price) - ((this.newDiscount * (this.edit[0].quantity * this.edit[0].price)) / 100);
    }

    setNewDiscount() {
        if (!this.newDiscount && this.edit[0])
            this.newDiscount = this.edit[0].discount;
    }

    updateDiscount() {
        let salesIds = [];
        let modified = false;
        for (let i = 0; i < this.edit.length; i++) {
            if (this.newDiscount != this.edit[0].discount || this.bulk || !this.newDiscount) {
                salesIds.push(this.edit[i].id);
                modified = true;
            }
        }

        if (modified) {
            const params = {salesIds: salesIds, newDiscount: this.newDiscount};
            const query = `Tickets/${this.$state.params.id}/updateDiscount`;
            this.$http.post(query, params).then(() => {
                this.vnApp.showSuccess(this.$translate.instant('Data saved!'));
                this.clearDiscount();
                modified = false;
                // this.vnTicketSale.$scope.model.refresh();
            }).catch(e => {
                this.vnApp.showError(e.message);
            });

            this.onHide();
        } else
            this.vnApp.showError(this.$translate.instant('There are no changes to save'));
    }

    clearDiscount() {
        this.newDiscount = null;
    }
}

Controller.$inject = ['$scope', '$http', '$state', 'vnApp', '$translate'];

ngModule.component('vnTicketSaleEditDiscount', {
    template: require('./editDiscount.html'),
    controller: Controller,
    bindings: {
        edit: '<?',
        mana: '<?',
        bulk: '<?',
        onHide: '&'
    }
});