import _ from 'lodash';
import { requestApi } from 'lib/requestApi';
import ApplicationStore from 'stores/Application';
import AuthStore from 'stores/Auth';
import GroupStore from 'stores/Groups';

const api = {
    read,
    readFlat,
    getList,
    getMembers,
    getAdmins,
    create,
    update,
    remove,
};

_.set(window.ya.connect, 'api.group', api);

export default api;

function read(options) {
    const query = _.clone(options) || {};
    let subsection = query.subsection;

    if (query.extension === 'auto') {
        query.extension = GroupStore.get(query.id) ? 'shallow' : 'deep';
    }

    if (subsection === 'auto') {
        subsection = ApplicationStore.getSubsectionName();
    }

    switch (subsection) {
        case 'admin':
            query.admin_uid = AuthStore.getUserId();
            break;
        case 'member':
            query.member_uid = AuthStore.getUserId();
            break;
    }

    if (!query.type) {
        query.type = 'generic';
    }

    if (query.subsection) {
        delete query.subsection;
    }

    return requestApi('GET', 'group', { query, tag: subsection });
}

function readFlat(options) {
    return requestApi('GET', 'flatgroup', { query: options, tag: 'flat_group' });
}

function getList(options) {
    return requestApi('GET', 'groups', { query: options });
}

function getMembers(options) {
    return requestApi('GET', 'group/members', { query: options });
}

function getAdmins() {
    const query = {
        type: 'organization_admin',
    };

    return requestApi('GET', 'group', { query });
}

function create(data) {
    return requestApi('POST', 'group', { data });
}

function update(data, id) {
    return requestApi('PATCH', 'group', { query: { id }, data });
}

function remove(id) {
    return requestApi('DELETE', 'group', { query: { id } });
}
