import React, { ReactElement } from 'react';
import ReactDOM from 'react-dom';
import { tap } from 'rxjs/operators';

import { GQL_STATE_ID, SSR_PAGES } from './vars';

import { app, PluginFn } from './index';

const initialGQLState = readJson(GQL_STATE_ID);
const pages = readJson(SSR_PAGES);
const { search, pathname } = window.location;

export function initBrowser(el: ReactElement, plugins: PluginFn[] = []) {
    const storeState = {};
    return app(pathname, search, initialGQLState, pages, storeState, el, plugins).pipe(
        tap(({ response, app }) => {
            switch (response.kind) {
                case 'not-found':
                case 'success': {
                    if (!app) {
                        console.error('app is missing from return');
                        return false;
                    }
                    if ((module as any).hot) {
                        ReactDOM.render(app, document.getElementById('root'));
                    } else {
                        ReactDOM.hydrate(app, document.getElementById('root'));
                    }
                    break;
                }
                case 'error': {
                    // todo: what to do if an error makes it this far?
                    console.error(response.statusCode, response.message);
                    break;
                }
                case 'redirect': {
                    // eslint-disable-next-line no-console
                    console.log('should redirect from browser here');
                    window.location.href = response.location;
                    break;
                }
            }
        }),
    );
}

function readJson(selector: string) {
    const elem = document.getElementById(selector);
    try {
        if (!elem) {
            return {};
        }
        return JSON.parse(elem.textContent || '');
    } catch (e) {
        console.error(e);
        return {};
    }
}
