import SubscriptionServiceModal from 'components2/ServiceToggleModal/SubscriptionService';
import EnabledServiceModal from 'components2/ServiceToggleModal/EnabledService';
import { PricingStore } from 'lib2/stores';
import getService from 'lib2/getService';
import directory from 'api2/directory';
import notify from 'lib2/notify';
import ServiceStatusPolling from 'lib2/ServiceStatusPolling';
import { i18n } from 'i18n2';

function withToggleRequest(serviceSlug, targetStatus, onConfirm, onToggle) {
    return params => {
        if (onConfirm) {
            onConfirm(targetStatus);
        }

        directory
            .send('POST', `/v11/services/${serviceSlug}/${targetStatus ? 'enable' : 'disable'}/`, {
                body: params && JSON.stringify(params),
            })
            .then(({ ok, body }) => {
                if (!ok) {
                    let message = i18n(`backend_errors.${body.code}`) ||
                        i18n('services.error.failed_to_enable');

                    return notify(message, 'error');
                }

                if (onToggle) {
                    onToggle();
                }

                ServiceStatusPolling.start();
            });
    };
}

export default ({ serviceSlug, targetStatus, onConfirm, onCancel, onToggle }) => {
    let prefetch = Promise.resolve();
    let { trial, with_subscriptions: withSubscriptions } = getService(serviceSlug);
    let hasTrial = Boolean(trial && trial.expiration_date);

    onConfirm = withToggleRequest(serviceSlug, targetStatus, onConfirm, onToggle);

    if (withSubscriptions && hasTrial) {
        if (!PricingStore.get(['services', serviceSlug])) {
            prefetch = directory
                .send('GET', '/v11/subscription/pricing/')
                .then(({ body }) => {
                    PricingStore.mergeState(body);
                });
        }

        return prefetch.then(() => ({
            ModalComponent: SubscriptionServiceModal,
            modalProps: { serviceSlug, targetStatus, onConfirm, onCancel },
        }));
    }

    if (targetStatus) {
        return prefetch.then(() => onConfirm());
    }

    return prefetch.then(() => ({
        ModalComponent: EnabledServiceModal,
        modalProps: { serviceSlug, onConfirm, onCancel },
    }));
};
