import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';
import Url from 'lib/Url';

import orgApi from 'api/org';
import domainApi from 'api/domain';
import getErrors from 'lib/getErrors';

export default {
    update,
    changeMasterDomain,
    addDomain,
    removeDomain,
};

function start() {
    dispatcher.dispatch(ActionTypes.START_SETTINGS_PROCESS);
}

function succeed(response) {
    if (response) {
        dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);
    }
    dispatcher.dispatch(ActionTypes.END_SETTINGS_PROCESS);
}

function fail(error) {
    dispatcher.dispatch(ActionTypes.END_SETTINGS_PROCESS);

    throw error;
}

/**
 * Изменение основного домена организации
 * @param {String} domain
 * @returns {Promise}
 */
function changeMasterDomain(domain) {
    start();

    return orgApi.changeMasterDomain(domain)
        .then(() => window.location.reload())
        .catch(fail);
}

function update(orgData) {
    return orgApi.update(orgData)
        .then(response => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

            return response;
        })
        .catch(fail);
}

/**
 * Удаление домена
 * @param {String} domain
 * @returns {Promise}
 */
function removeDomain(domain) {
    start();

    return domainApi.remove(domain)
        .then(response => {
            const errors = getErrors(response);

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

            succeed(response);
        })
        .catch(error => {
            dispatcher.dispatch(ActionTypes.END_SETTINGS_PROCESS);

            if (error && error.response) {
                return error.response.json()
                    .then(data => {
                        if (data && data.code) {
                            error.code = data.code;
                        }
                        throw error;
                    })
                    .catch(() => {
                        throw error;
                    });
            }

            throw error;
        });
}

/**
 * Добавление домена
 * @param {String} domain
 * @returns {Promise}
 */
function addDomain(domain) {
    start();

    return domainApi.add(domain)
        .then(response => {
            if (response && response.originalError) {
                const error = new Error();

                error.response = response;
                error.status = response.status;
                throw error;
            }

            succeed();
            Url.open(Url.getDomainSettingsPath(domain));

            return response;
        })
        .catch(fail);
}
