import { Promise } from 'rsvp';
import OrganizationStore from 'stores/Organizations';

import userApi from 'api/user';
import domainApi from 'api/domain';
import dnsApi from 'api/dns';
import { start, succeed, succeedAll, fail } from './handlers';

export default {
    showDns,
    showOrgAdmin,
    showDomainSettings,
    showAdminList,
    showDomains,
};

function showDns(domain) {
    start();

    const domainPromise = domainApi.getList();
    const dnsPromise = domainPromise
        .then(() => {
            if (!domain) {
                domain = OrganizationStore.getMasterDomain();
            }

            return dnsApi.getRecords(domain);
        });

    return Promise.all([
        domainPromise,
        dnsPromise,
    ])
        .then(succeedAll)
        .catch(fail);
}

function showOrgAdmin(id) {
    start();

    return userApi.read({ id, extension: 'shallow' }).then(succeed)
        .catch(fail);
}

/**
 * Показываем настройки организации
 * @returns {Promise}
 */
function showDomainSettings() {
    start();

    return domainApi.getList().then(succeed)
        .catch(fail);
}

/**
 * Показываем список доменов
 * @returns {Promise}
 */
function showDomains() {
    start();

    return domainApi.getList().then(succeed)
        .catch(fail);
}

/**
 * Показываем список администраторов
 * @returns {Promise}
 */
function showAdminList() {
    start();

    return userApi.getList({ role: 'admin' }).then(succeed)
        .catch(fail);
}
