import _ from 'lodash';
import { requestApi, requestServiceApi } from 'lib/requestApi';
import ApplicationStore from 'stores/Application';
import UserStore from 'stores/Users';

const DEFAULT_ADMIN_LIST_QUERY = {
    page: 1,
    role: 'admin',
    ordering: 'name',
};

const api = {
    getList,
    getAdminList,
    read,
    create,
    update,
    updateList,
    addAlias,
    removeAlias,
    setAvatar,
    getSK,
};

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

export default api;

const USER_SCHEMA = [
    'name',
    'contacts',
    'recovery_email',
    'aliases',
    'department_id',
    'nickname',
    'name',
    'password',
    'password_change_required',
    'position',
    'is_enabled',
    'is_dismissed',
    'role',
    'birthday',
    'timezone',
    'gender',
    'language',
];

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

function getAdminList(options) {
    return requestApi('GET', 'users', {
        query: _.extend({}, DEFAULT_ADMIN_LIST_QUERY, options),
    });
}

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

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

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

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

function create(data) {
    data = _.omit(data, 'password_confirmation');

    return requestApi('POST', 'user', { data });
}

function update(data, id) {
    data = _.pick(data, USER_SCHEMA);

    return requestApi('PATCH', 'user', { query: { id }, data });
}

function updateList(data) {
    return requestApi('POST', 'users', { data });
}

function addAlias(alias, id) {
    const data = { name: alias };

    return requestApi('POST', 'user/alias', { query: { id }, data });
}

function removeAlias(alias, id) {
    const query = { id, name: alias };

    return requestApi('DELETE', 'user/alias', { query });
}

function setAvatar(data, id) {
    return requestApi('POST', 'user/avatar', { query: { id }, data, timeout: 60000 });
}

function getSK() {
    return requestServiceApi('GET', 'sk');
}
