import _ from 'lodash';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import getErrors from 'lib/getErrors';
import mailApi from 'api/mail';
import toFormData from 'lib/toFormData';

export default {
    getSettings,
    updateSettings,
    getDkimStatus,
    enableDkim,
    checkImportServer,
    startImport,
    getImportStatus,
    checkImportStatus,
    stopImportStatusCheck,
};

function resolve(response) {
    const errors = getErrors(response);

    if (!errors.isEmpty()) {
        return { errors };
    }

    dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

    return response;
}

function getSettings() {
    return mailApi.getSettings().then(resolve);
}

function updateSettings(data) {
    return mailApi.updateSettings(data)
        .then(response => {
            const errors = getErrors(response);

            if (!errors.isEmpty()) {
                return { errors };
            }

            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, { mail_settings: data });

            return { mail_settings: data };
        });
}

function getDkimStatus(domain) {
    return mailApi.getDkimStatus(domain).then(resolve);
}

function enableDkim(domains) {
    return mailApi.enableDkim(domains)
        .then(() => mailApi.getDkimStatus())
        .then(resolve);
}

function checkImportServer(options) {
    return mailApi.checkImportServer(options).then(resolve);
}

function startImport(options = {}) {
    let data;

    if (options.migration_file) {
        data = toFormData(options, { files: ['migration_file'] });
    }

    return mailApi.startImport(data || options)
        .then(response => {
            if (getErrors(response).isEmpty()) {
                dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);
            }

            return response;
        });
}

function getImportStatus(options) {
    return mailApi.getImportStatus(options).then(resolve);
}

const IMPORT_STATUS_CHECK_TIME = 5000;
let isImportCheckRunning;

function checkImportStatus(options) {
    const run = () => {
        getImportStatus(options).then(response => {
            const status = _.get(response, 'mail_import.status');

            if (!response || response.errors || status === 'failed') {
                isImportCheckRunning = false;

                return;
            }

            const progress = _.get(response, 'mail_import.progress', []);
            const complete = progress.length && (
                _.every(progress, ['state', 'success']) ||
                _.some(progress, ['state', 'failed'])
            );

            if (complete) {
                isImportCheckRunning = false;
            }

            if (isImportCheckRunning) {
                setTimeout(run, IMPORT_STATUS_CHECK_TIME);
            }
        });
    };

    if (!isImportCheckRunning) {
        isImportCheckRunning = true;
        run();
    }
}

function stopImportStatusCheck() {
    isImportCheckRunning = false;
}
