import _ from 'lodash';
import { requestApi } from 'lib/requestApi';
import ApplicationStore from 'stores/Application';
import DepartmentStore from 'stores/Departments';

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

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

export default api;

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

    if (query.extension === 'auto') {
        const department = DepartmentStore.get(query.id);
        const parentDepartment = {
            id: department ? department.get('parent') : null,
            type: 'department',
        };

        query.extension = ApplicationStore.hasOpen(parentDepartment) ? 'shallow' : 'deep';
    }

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

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

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

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

function update(data, id) {
    return requestApi('PUT', 'department', { query: { id }, data });
}

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

function addMembers(data, id) {
    return requestApi('POST', 'department/members', { query: { id }, data });
}
