import { setStrataHeaders } from '@rh-support/api';
import get from 'lodash/get';
import React from 'react';
import ReactDOM from 'react-dom';
import { HashRouter, Route } from 'react-router-dom';
import App from './App';
import RootProvider from './context/RootProvider';
import './scss/index.scss';

declare global {
    interface Window {
        MSInputMethodContext: any;
        chrometwo_require: (component: string[], callback: (...params) => any) => any;
        portal: any;
        Raven: any;
        chrometwo_ready: any;
        seVersionInfo: {
            gitTag: string,
            packageVersion: string,
            hydrajs: string,
        };
    }

    interface Document {
        documentMode: any;
    }
}
window.seVersionInfo = {
    gitTag: GIT_TAG,
    packageVersion: PACKAGE_VERSION,
    hydrajs: HYDRAJS_VERSION,
};

window.chrometwo_require(['session', 'analytics/main', 'analytics/attributes'], (session, paf, pafAttrs) => {
    if (session) {
        session.onInit(() => {
            // Login on app load if needed
            if (!session.isAuthenticated()) {
                session.login();
                return;
            }
            // Hydrajs needs  session inside  sessionjs variable
            window.sessionjs = session;
            setStrataHeaders('Solution Engine', get(window, 'seVersionInfo.gitTag'), window.sessionjs.getToken().account_number);

            //  dtm related
            paf.init(['dtm']);
            pafAttrs.harvest();
            paf.report();

            // App initialization
            window.chrometwo_ready(() => {
                ReactDOM.render(
                    <HashRouter>
                        <RootProvider>
                            <Route exact={false} path="/" component={App} />
                        </ RootProvider>
                    </HashRouter>,
                    document.getElementById('se-solution-engine')
                );
            });
        });
    } else {
        // tslint:disable-next-line:no-console
        console.error('unable to initialize the sessionjs');
    }
});

if ((module as any).hot) {
    (module as any).hot.accept();
}
