const _ = require('lodash');
const sendHandledRequest = require('../../lib/sendHandledRequest');
const stackResponse = require('../../lib/stackResponse');

const DEPARTMENT_FIELDS = [
    'is_outstaff', 'head', 'head.about', 'head.name', 'head.contacts', 'head.gender', 'head.external_id',
    'head.department_id', 'head.email', 'head.birthday', 'head.is_admin', 'head.position', 'head.login',
    'head.is_dismissed', 'head.aliases', 'members_count', 'description', 'head.nickname ',
    'parent', 'created', 'label', 'email', 'maillist_type', 'parents', 'uid', 'removed', 'external_id', 'id', 'name',
    'parent.parent_id', 'parent.removed', 'parent.external_id', 'parent.name',
    'parents.created', 'parents.description', 'parents.members_count', 'parents.parent_id', 'parents.removed',
    'parents.external_id', 'parents.name', 'parents.label', 'parents.email', 'parents.maillist_type', 'parents.uid',
];

function read(req, res, next) {
    return sendHandledRequest({
        method: 'get',
        url: [req.config.api.directory, 'v9', 'departments', { value: req.query.id, type: 'number' }],
        source: req,
        query: { fields: DEPARTMENT_FIELDS.join(',') },
        label: 'read_department',
    })
        .then(department => {
            stackResponse(req.context, 'departments', department);

            return next ? next() : req;
        })
        .catch(next);
}

function create(req, res, next) {
    return sendHandledRequest({
        method: 'post',
        url: [req.config.api.directory, 'departments'],
        source: req,
        label: 'create_department',
    })
        .then(department => {
            stackResponse(req.context, 'departments', department);

            return next ? next() : req;
        })
        .catch(next);
}

function update(req, res, next) {
    return sendHandledRequest({
        method: 'patch',
        url: [req.config.api.directory, 'departments', { value: req.query.id, type: 'number' }],
        source: req,
        label: 'update_department',
    })
        .then(department => {
            stackResponse(req.context, 'departments', department);

            return next ? next() : req;
        })
        .catch(next);
}

function remove(req, res, next) {
    return sendHandledRequest({
        method: 'delete',
        url: [req.config.api.directory, 'departments', { value: req.query.id, type: 'number' }],
        source: req,
        label: 'remove_department',
    })
        .then(() => next ? next() : req)
        .catch(next);
}

// basic query: { parent_id, page, per_page }
function readList(req, res, next) {
    const defaultOptions = {
        per_page: _.get(req.config, 'directory.perPage.default'),
        ordering: 'name',
    };
    const query = _.extend(defaultOptions, req.query);

    return sendHandledRequest({
        method: 'get',
        url: [req.config.api.directory, 'departments'],
        query,
        source: req,
        label: 'read_department_list',
    })
        .then(departmentList => {
        /*
        // если родительский отдел не попадает в список отделов,
        // находим данные о нем в его поддотделе и добавляем их в список
        if (departmentList.result && departmentList.result.length) {
            var rootSubdepartment = _.find(
                departmentList.result,
                department => _.get(department, 'parent.id') === 1
            );
            if (rootSubdepartment) {
                var rootDepartment = _.cloneDeep(rootSubdepartment.parent);
                departmentList.result.push(rootDepartment);
            }
        }
        */

            const list = _.extend(departmentList, { type: 'departments', query });

            stackResponse(req.context, 'lists', list);

            return next ? next() : req;
        })
        .catch(next);
}

function createLinkCode(req, res, next) {
    const { departmentId } = req.body;

    return sendHandledRequest({
        method: 'post',
        url: `${req.config.api.directory}/departments/${departmentId}/invite`,
        source: req,
        label: 'create_invite_code',
    })
        .then(({ code }) => {
            req.context.invites = {
                code,
            };

            return next ? next() : req;
        })
        .catch(next);
}

function removeLinkCode(req, res, next) {
    const { departmentId } = req.body;

    return sendHandledRequest({
        method: 'delete',
        url: `${req.config.api.directory}/departments/${departmentId}/invite`,
        source: req,
        label: 'remove_invite_code',
    })
        .then(() => next ? next() : req)
        .catch(next);
}

function readLinkCode(req, res, next) {
    const { departmentId } = req.query;

    return sendHandledRequest({
        method: 'get',
        url: `${req.config.api.directory}/departments/${departmentId}/invite`,
        source: req,
        label: 'read_invite_code',
    })
        .then(({ code }) => {
            req.context.invites = {
                code,
            };

            return next ? next() : req;
        })
        .catch(err => {
            if (err && err.statusCode === 404) {
                req.context.invites = {
                    code: null,
                };

                return next ? next() : req;
            }

            throw err;
        })
        .catch(next);
}

module.exports = {
    read,
    create,
    update,
    remove,
    readList,
    createLinkCode,
    removeLinkCode,
    readLinkCode,
};
