import _ from 'lodash';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import resourcesApi from 'api/resources';
import permissionsApi from 'api/permissions';
import getErrors from 'lib/getErrors';

export default {
    read,
    count,
    remove,
    createRelation,
    removeRelation,
    confirmRequest,
    denyRequest,
};

function receiveResponse(response) {
    const errors = getErrors(response);

    if (!errors.isEmpty()) {
        return { errors };
    }

    dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

    return response;
}

function read({ service }) {
    return resourcesApi.read({ service })
        .then(receiveResponse);
}

function count({ service }) {
    return resourcesApi.count({ service })
        .then(receiveResponse);
}

function remove(data) {
    dispatcher.dispatch(ActionTypes.START_PROCESS);

    return resourcesApi.remove(data)
        .then(response => {
            dispatcher.dispatch(ActionTypes.END_PROCESS);

            return receiveResponse(response);
        });
}

function createRelation(data) {
    return resourcesApi.createRelation(data)
        .then(receiveResponse);
}

function removeRelation(data) {
    return resourcesApi.removeRelation(data)
        .then(removeResponse => {
            if (!data || !data.service || !data.resource_id) {
                return receiveResponse(removeResponse);
            }

            return permissionsApi.getList({
                type: data.service,
                id: data.resource_id,
            }).then(permissionResponse => {
                permissionResponse.permissions.local = {
                    resource: permissionResponse.permissions.local,
                };

                return receiveResponse(_.merge({}, removeResponse, permissionResponse));
            });
        });
}

function confirmRequest(data) {
    return resourcesApi.confirmRequest(data)
        .then(receiveResponse);
}

function denyRequest(data) {
    return resourcesApi.denyRequest(data)
        .then(receiveResponse);
}
