import ngModule from '../module';
import './style.scss';

class Controller {
    constructor($http, $state, $scope, aclService) {
        this.aclService = aclService;
        this.$http = $http;
        this.$state = $state;
        this.$ = $scope;
        this.itemSelected = null;
        this.imagesPath = '//verdnatura.es/vn-image-data/catalog';

        this.showFields = {
            id: false,
            actions: false
        };
        this.moreOptions = [
            {callback: this.goToTicketRequest, name: 'Buy requests', acl: 'buyer'}
        ];
    }

    onMoreOpen() {
        let options = this.moreOptions.filter(o => this.aclService.hasAny([o.acl]));
        this.$.moreButton.data = options;
    }

    onMoreChange(callback) {
        callback.call(this);
    }

    goToTicketRequest() {
        this.$state.go('item.request');
    }

    stopEvent(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
    }

    onSearch(params) {
        if (params && params.hasVisible === undefined && params.isActive === undefined)
            Object.assign(params, {hasVisible: true, isActive: true});

        if (params)
            this.$.model.applyFilter(null, params);
        else
            this.$.model.clear();
    }

    showItemDescriptor(event, itemFk) {
        if (event.defaultPrevented) return;

        event.preventDefault();
        event.stopPropagation();

        this.$.itemDescriptor.itemFk = itemFk;
        this.$.itemDescriptor.parent = event.target;
        this.$.itemDescriptor.show();
    }


    showWorkerDescriptor(event, workerFk) {
        if (event.defaultPrevented) return;

        event.preventDefault();
        event.stopPropagation();

        this.selectedWorker = workerFk;
        this.$.workerDescriptor.parent = event.target;
        this.$.workerDescriptor.show();
    }

    cloneItem(event, item) {
        this.stopEvent(event);
        this.itemSelected = item;
        this.$.clone.show();
    }

    onCloneAccept(response) {
        if (!(response == 'ACCEPT' && this.itemSelected))
            return;

        this.$http.post(`/item/api/Items/${this.itemSelected.id}/clone`).then(res => {
            if (res && res.data && res.data.id)
                this.$state.go('item.card.tags', {id: res.data.id});
        });

        this.itemSelected = null;
    }

    preview(event, item) {
        this.stopEvent(event);
        this.itemSelected = item;
        this.$.preview.show();
    }
}
Controller.$inject = ['$http', '$state', '$scope', 'aclService'];

ngModule.component('vnItemIndex', {
    template: require('./index.html'),
    controller: Controller
});