const _ = require('lodash');
const organization = require('../organization');

const sendHandledRequest = require('../../../lib/sendHandledRequest');

const setOrgLogo = require('./profile.logo.file');
const setOrgLogoUrl = require('./profile.logo.url');

function getCurrentOrganization(req) {
    const orgs = _.get(req, 'context.organizations', []);
    const currentOrgId = _.get(req, 'context.state.organization');
    const currentOrg = _.find(orgs, org => String(org.id) === currentOrgId);

    return currentOrg;
}

function read(req, res, next) {
    return sendHandledRequest({
        method: 'get',
        url: [req.config.api.directory, 'ui', 'org-profile'],
        source: req,
        label: 'read_organization_profile',
    })
        .then(response => {
            const org = getCurrentOrganization(req);

            if (org) {
                _.merge(org, response);
            }

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

function update(req, res, next) {
    return organization.update(req, res)
        .then(() => organization.read(req))
        .then(() => next ? next() : req)
        .catch(next);
}

function setLogo(req, res, next) {
    if (req.body.logo_url) {
        return setOrgLogoUrl(req, res, next);
    }

    return setOrgLogo(req, res, next);
}

function removeLogo(req, res, next) {
    const orgId = req.query.id || req.get('x-org-id');

    return sendHandledRequest({
        method: 'delete',
        url: [
            req.config.api.directory, 'organizations',
            { value: orgId, type: 'number' }, 'change-logo',
        ],
        source: req,
        label: 'remove_organization_logo',
    })
        .then(() => next ? next() : req)
        .catch(next);
}

module.exports = {
    read, update, setLogo, removeLogo,
};
