import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { createHttpLink } from 'apollo-link-http';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloProvider } from 'react-apollo';
import Nav from './components/nav';
import { ApolloLink, split, NextLink } from 'apollo-link';
import { Fragment } from 'react';
import { NavLink, Link, BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Homepage from './pages/home';
import history from './utils/history';
import BotBuilder from './pages/botbuilder';
import Callback from './pages/callback';
import Config from '@botsbotsbots/common/config';
import './stylesheets/bbb/nav.scss';
import { getIdToken, isLoggedIn } from './utils/auth';
const link = createHttpLink({
	uri: Config.app.api
});

const middlewareLink = new ApolloLink((operation, forward: NextLink) => {
	// get the authentication token from local storage if it exists
	const id_token = getIdToken();
	// return the headers to the context so httpLink can read them
	operation.setContext({
		headers: {
			Authorization: id_token ? `Bearer ${id_token}` : ''
		}
	});
	return forward(operation);
});

const client = new ApolloClient({
	cache: new InMemoryCache(),
	link: ApolloLink.from([middlewareLink.concat(link)])
});

const WithProvider = (client) => (
	<ApolloProvider client={client}>
		<Router>
			<Fragment>
				{<Nav />}
				<div className="fl w-100 pl4 pr4">
					<Switch>
						<Route exact path="/" component={Homepage} />
						<Route path="/callback" component={Callback} />
						<Route path="/bots/:emoji_id" component={BotBuilder} />
						<Route path="/bots" component={BotBuilder} />
					</Switch>
				</div>
			</Fragment>
		</Router>
	</ApolloProvider>
);

function withAuth() {
	return ReactDOM.render(WithProvider(client), document.getElementById('root') as HTMLElement);
}

withAuth();
