import { Promise } from 'rsvp';
import { Service } from 'lib/services';

import AuthStore from 'stores/Auth';
import domainApi from 'api/domain';
import subscriptionApi from 'api/subscription';
import resourcesApi from 'api/resources';
import CommonAppActions from './Common';
import { succeed } from './handlers';

export default {
    showDashboard,
};

const ServicesWithCounters = [
    'metrika', 'direct', 'yandexsprav',
];

function showDashboard() {
    ServicesWithCounters.reduce((chain, serviceSlug) => {
        if (Service.isEnabled(serviceSlug)) {
            // асинхронно, не блокирует возвращаемый методом промис
            chain = chain.then(() => resourcesApi.count({ service: serviceSlug }).then(succeed));
        }

        return chain;
    }, Promise.resolve());

    if (AuthStore.isAdmin()) {
        domainApi.getList()
            .then(succeed);

        subscriptionApi.getState()
            .then(succeed);
    }

    return CommonAppActions.performDefaultAction();
}
