import _ from 'lodash';
import { ActionTypes } from 'constants/Common';
import { SERVICES_WITH_LICENSES } from 'constants/Services';
import dispatcher from 'dispatcher';
import servicesApi from 'api/services';
import permissionsApi from 'api/permissions';
import getErrors from 'lib/getErrors';
import { i18n } from 'lib/i18n';

import ModalActions from 'actions/Modal';
import subscriptionApi from 'api/subscription';
import SubscriptionStore from 'stores/Subscription';
import SubscriptionServiceToggle from 'components/SubscriptionServiceToggle';

export default {
    update,
    toggle,
};

function receiveResponse(response) {
    const errors = getErrors(response);

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

    dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);

    return response;
}

function update(service, data) {
    return servicesApi.update(service, data)
        .then(updateResponse => permissionsApi.getServiceList(service)
            .then(permissionResponse => receiveResponse(_.merge({}, updateResponse, permissionResponse))));
}

function getText(key, serviceSlug) {
    return i18n(`service_page.${serviceSlug}.toggle.${key}`) ||
        i18n(`service_page.default.toggle.${key}`);
}

function toggle({ serviceSlug, isEnabled, onSubmit }) {
    const isSubscriptionService = SERVICES_WITH_LICENSES.indexOf(serviceSlug) !== -1;

    if (isSubscriptionService) {
        let pricingPromise = Promise.resolve();

        if (!SubscriptionStore.get('pricing')) {
            pricingPromise = subscriptionApi.getPricing()
                .then(response => {
                    dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, response);
                });
        }

        return pricingPromise
            .then(() => {
                ModalActions.open({
                    title: getText(`title.${isEnabled ? 'on' : 'off'}`, serviceSlug),
                    component: SubscriptionServiceToggle,
                    props: {
                        serviceSlug,
                        onConfirm: params => {
                            ModalActions.close();
                            onSubmit(params);
                        },
                    },
                });
            });
    }

    if (!isEnabled) {
        return Promise.resolve().then(() => {
            onSubmit();
        });
    }

    return Promise.resolve().then(() => {
        ModalActions.confirm({
            title: getText('title.on', serviceSlug),
            message: getText('description.on.without_trial', serviceSlug),
            mod: 'warning',
            onConfirm: () => onSubmit(),
            confirmButtonText: getText('disable', serviceSlug),
            rejectButtonText: i18n('common.action.cancel'),
        });
    });
}
