const fs = require('fs');
const formidable = require('formidable');

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

const API_ROOT = config.api.directory;
const MAX_FILE_SIZE = 7 * 1024 * 1024;

const EXTENSION_MAP = {
    jpeg: 'jpg',
};

function setOrgLogo(req, res, next) {
    const form = new formidable.IncomingForm();

    form.maxFieldsSize = MAX_FILE_SIZE;

    const receive = new Promise((resolve, reject) => {
        let receivedFile;

        form.on('file', (name, file) => {
            if (name === 'logo_file') {
                receivedFile = file;
            }
        });

        form.on('end', () => {
            if (receivedFile) {
                resolve(receivedFile);
            } else {
                reject();
            }
        });
    });

    const send = file => {
        const orgId = req.query.id || req.get('x-org-id');
        const suffix = String(Math.floor(1e8 * Math.random()));

        const type = (file.type.match(/^[^\/]+\/([^\/]+)$/) || [])[1];
        const extension = EXTENSION_MAP[type] || type;

        return sendHandledRequest({
            method: 'post',
            url: [
                API_ROOT, 'organizations', { value: orgId, type: 'number' },
                'change-logo',
            ],
            formData: {
                logo_file: {
                    value: fs.createReadStream(file.path),
                    options: {
                        filename: `logo-${orgId}-${suffix}.${extension}`,
                        contentType: file.type,
                    },
                },
            },
            body: null,
            source: req,
            label: 'set_organization_logo',
        })
        // после отправки файла удаляем локальную копию
            .then(() => {
                if (fs.existsSync(file.path)) {
                    fs.unlink(file.path);
                }
            });
    };

    form.parse(req);

    return receive.then(send)
        .then(() => next ? next() : req)
        .catch(next);
}

module.exports = setOrgLogo;
