import React from 'react';
import { Promise } from 'rsvp';
import bemRegister from 'react-bem-components/lib/register';
import { ActionTypes } from 'constants/Common';
import enableErrorLogging from 'lib/enableErrorLogging';
import enableSessionCheck from 'lib/enableSessionCheck';

import dispatcher from 'dispatcher';

import Metrika from 'lib/metrika';
import rum, { RouteTiming } from 'lib/rum';
import timer from 'lib/timer';

// import 'url-polyfill';

export default {
    initialize,
};

// @fixme https://github.com/shama/webpack-stream/issues/102
if (!window.React) {
    window.React = React;
}

// полифилл whatwg-fetch для fetch в IE опирается на Promise из глобального скоупа
if (!window.Promise) {
    window.Promise = Promise;
}

function initialize() {
    timer.start('first_run');

    const ya = window.ya;

    enableErrorLogging();
    enableSessionCheck();

    dispatcher.dispatch(ActionTypes.RECEIVE_MIXED_DATA, ya.connect.initial);
    dispatcher.dispatch(ActionTypes.RECEIVE_CONFIG_DATA, ya.connect.config);

    ya.connect.v = ya.connect.config.app.version;

    window.yc = ya.connect;

    return new Promise(resolve => {
        modules.require(['BEMHTML', 'i-bem__dom', 'jquery'], (bh, ibem, jQuery) => {
            bh.setOptions({ escapeContent: true });
            bemRegister({ bh, ibem, jQuery });

            Metrika.init();

            rum.mark('layout.init');
            RouteTiming.start();

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