import _ from 'lodash';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import licenseRequestsApi from 'api/license.requests';
import LicensesActions from 'actions/Licenses';
import licensesApi from 'api/licenses';

export default {
    read,
    update,
    add,
};

function add(data) {
    licenseRequestsApi.add(data)
        .then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response;
        });
}

function read() {
    return licenseRequestsApi.read()
        .then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response;
        });
}

function update(data) {
    const updatePromise = licenseRequestsApi.update(data)
        .then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response;
        });

    if (data.action === 'deny') {
        return updatePromise;
    }

    return updatePromise.then(() => licensesApi.read())
        .then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            const currentSubscriptions = _.get(response, 'licenses.subscribers.tracker', []);

            return LicensesActions.calculate('tracker', currentSubscriptions.concat(data.requests));
        })
        .then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response;
        });
}
