import _ from 'lodash';
import resourcesApi from 'api/resources';
import permissionsApi from 'api/permissions';
import { start, succeed, fail } from './handlers';

export default {
    show,
    loadResource,
};

function show(service) {
    start();

    return Promise.all([
        resourcesApi.read({ service }),
        permissionsApi.getServiceList(service),
    ])
        .then(([resourcesResponse, permissionsResponse]) =>
            succeed(_.merge({}, resourcesResponse, permissionsResponse)))
        .catch(fail);
}

function loadResource(service, id) {
    start();

    return Promise.all([
        resourcesApi.readRelations({ service, resource_id: id }),
        resourcesApi.readRoles({ service, resource_id: id }),
        resourcesApi.readRequests({ service, resource_id: id }),
        permissionsApi.getServiceList(service),
        permissionsApi.getList({ type: service, id }),
    ])
        .then(requests => {
            const resourcePermissionsResponse = requests.pop();

            resourcePermissionsResponse.permissions.local = {
                resource: resourcePermissionsResponse.permissions.local,
            };

            return succeed(_.merge({}, ...requests, resourcePermissionsResponse));
        })
        .catch(fail);
}
