import _ from 'lodash';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import Url from 'lib/Url';
import getErrors from 'lib/getErrors';
import groupApi from 'api/group';

import AppActions from 'actions/App/OrgStructure';

export default {
    createGroup,
    updateGroup,
    removeGroup,
    getList,
    getMembers,
};

/**
 * Создание нового команды
 * @method  createGroup
 * @param   {Object}   data
 * @returns {Promise}
 */
function createGroup(data) {
    return groupApi.create(data).then(response => {
        const errors = getErrors(response);

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

        const id = (_.find(response.sources, { type: 'group' }) || {}).id;

        if (id) {
            Url.open(Url.getGroupPath('all', id));
        }
    });
}

/**
 * Обновление данных об команде
 * @method updateGroup
 * @param  {Object}    data
 * @param  {String}    id
 * @returns {Promise}
 */
function updateGroup(data, id) {
    return groupApi.update(data, id).then(response => {
        const errors = getErrors(response);

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

        dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);
        AppActions.showGroup('auto', id);
    });
}

/**
 * Удаление команды
 * @method removeGroup
 * @param  {String}    id
 * @returns {Promise}
 */
function removeGroup(id) {
    return groupApi.remove(id).then(response => {
        const errors = getErrors(response);

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

        dispatcher.dispatch(ActionTypes.DISCARD_GROUP, { id });
        Url.open(Url.getGroupListPath('auto'));
    });
}

function getList(options) {
    return groupApi.getList(options)
        .then(response => {
            const errors = getErrors(response);

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

            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response;
        });
}

function getMembers(options) {
    return groupApi.getMembers(options)
        .then(response => {
            const errors = getErrors(response);

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

            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response;
        });
}
