import {
    ConfigStore,
    FeatureStore,
    SessionStore,
    OrgStore,
    ServiceStore,
    PermissionStore,
    UserSettingsStore,
    OrgSettingsStore,
} from 'lib2/stores';
import rum, { RouteTiming } from 'lib2/rum';
import toServiceStoreState from 'lib2/toServiceStoreState';

export default () => {
    const yc = window.ya.connect;

    const { initial, config } = yc;
    const currentSession = (initial.sessions || {})[initial.state.session];

    ConfigStore.mergeState(config);

    SessionStore.mergeState({
        context: {
            uid: initial.state.session,
            org_id: initial.state.organization,
        },
        map: initial.sessions,
        current: currentSession,
        user: initial.currentUser || currentSession || {},
        karma: initial.karma,
        sk: initial.sk,
    });

    OrgStore.mergeState(initial.organizations);
    PermissionStore.mergeState(initial.permissions);
    FeatureStore.mergeState(initial.features);

    UserSettingsStore.mergeState(initial.user_settings);
    OrgSettingsStore.mergeState({
        ...initial.header_settings,
        ...initial.organization_settings,
    });

    if (initial.services && initial.services.length) {
        ServiceStore.mergeState(toServiceStoreState(initial.services));
    }

    yc.v = config.app.version;

    window.yc = yc;

    return new Promise(resolve => {
        rum.mark('layout.init');
        RouteTiming.start();

        rum.mark('before_js_framework_init');
        resolve(() => {
            rum.mark('js_framework_inited');
        });
    });
};
