import {ApiRequest, GET} from "../../lib/ApiRequest";
import {ApiEvent} from "../../lib/ApiEvent";

const evts = {};

class ApiProduct extends ApiEvent {

    constructor() {
        super(evts);
    }

    offList(evtName) {
        this.off('list', evtName);
    }

    triggerList() {
        this.trigger('list');
    }

    onList(group, stateUpdater, dataReceive, evtName = false) {
        const evt = () => {
            stateUpdater('progress');

            (new ApiRequest('api', GET, 'shop/group/' + group + '/product'))
                .debug(true)
                .exec()
                .then((res) => {
                    if(res && res.data) {
                        dataReceive(res.data);
                        stateUpdater(true);
                    } else {
                        stateUpdater('error');
                    }
                })
                .catch(() => {
                    stateUpdater('error');
                });
        };
        if(evtName) {
            this.on('list', evtName, evt);
        }

        evt();
    }
}

const apiProduct = new ApiProduct();

export default apiProduct;