import _ from 'lodash';
import { Promise } from 'rsvp';
import { ActionTypes } from 'constants/Common';
import dispatcher from 'dispatcher';

import Url from 'lib/Url';
import getErrors from 'lib/getErrors';
import domainApi from 'api/domain';
import AppActions from 'actions/App/OrgSettings';
import DomainStore from 'stores/Domains';

export default {
    addDomain,
    showDomain,
    checkDomainOwnership,
    getOwnershipInfo,
};

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;
}

function addDomain(data, isServicePage) {
    return domainApi.add(data.name).then(response => {
        const errors = getErrors(response);

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

        AppActions.showDomainSettings()
            .then(() => {
                const name = _.get(response, 'domain.name', data.name);

                if (isServicePage) {
                    Url.open(Url.getPath('services', 'webmaster', 'resources', name));

                    return;
                }
                Url.open(Url.getDomainSettingsPath(name));
            });
    });
}

/**
 * Показываем страницу домена
 * @param {String} domainName
 * @returns {Promise}
 */
function showDomain(domainName) {
    const domain = DomainStore.getDomain(domainName);

    // если домен есть в сторе и домен подтвержден, не дозапрашиваем о нем инфу
    if (domain && domain.isOwned()) {
        dispatcher.dispatch(ActionTypes.RECEIVE_APPLICATION_DATA, {});

        return Promise.resolve();
    }

    return Promise.all([
        domainApi.read(domainName),
        domainApi.getConfirmationInfo(domainName),
    ])
        .then(([readResponse, confirmationResponse]) => {
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, {
                domains: readResponse && readResponse.domains,
                confirmation: confirmationResponse && confirmationResponse.confirmation,
            });
        });
}

function getOwnershipInfo(domain) {
    return domainApi.getConfirmationInfo(domain)
        .then(response => {
            succeed();

            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);
            dispatcher.dispatch(ActionTypes.RECEIVE_APPLICATION_DATA, {});

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

function checkDomainOwnership(options) {
    start();

    return domainApi.checkOwnership(options)
        .then(response => {
            succeed();
            dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

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