import buildUrl from '@connect/url-placeholders';
import toMap from './toMap';
import truncateOwnHost from './truncateOwnHost';
import isAdmin from './isAdmin';
import { SessionStore, ConfigStore } from './stores';

function fixUrls(services) {
    services.forEach(service => {
        service.url = truncateOwnHost(service.url);
        service.settings_url = truncateOwnHost(service.settings_url);

        if (service.actions) {
            service.actions.forEach(action => {
                action.url = truncateOwnHost(action.url);
            });
        }

        // @see DIR-10291
        if (service.slug === 'mail') {
            service.settings_url = buildUrl(
                isAdmin() ?
                    ConfigStore.get('mail.admin') :
                    ConfigStore.get('mail.mail'),
                SessionStore.get('context')
            );
        }

        // @see DIR-10400
        if (service.slug === 'forms') {
            service.url = ConfigStore.get('ui.relatedServices.forms');
        }
    });

    return services;
}

export default function toServiceStoreState(services) {
    return {
        map: toMap(fixUrls(services), 'slug'),
        order: services.map(({ slug }) => slug),
    };
}
