// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
import { Router } from 'director/build/director';
import { autorun } from 'mobx';
import { IStoreWithBase, Routes } from '../context/context.interface';

/**
 * helper function that returns default routes for the app
 * @param store IStoreWithBase<T, V>
 * @returns default routes for the app
 */
function getDefaultRoutes<T>(store: IStoreWithBase<T>) {
  return {
    '/': () => {
      store.app.view.open('/', 'Home', () => {
        /** */
      });
    }
  };
}

/**
 * Start Director Router
 * @param {IStoreWithBase<T, V>} appStore
 * @param {Routes<T, V>} routes
 */
export function startRouter<T>(appStore: IStoreWithBase<T>, routes: Routes<T>) {
  const defaultRoutes = getDefaultRoutes<T>(appStore);

  const appRoutes = { ...defaultRoutes, ...routes(appStore) };
  // update state on url change
  new Router(appRoutes)
    .configure({
      before: () => {
        /** */
      },
      notfound: () => {
        appStore.app.view.open('/404', 'Not Found', () => {
          console.log('Not Found');
        });
      },
      html5history: true
    })
    .init();

  // update url on state changes
  autorun(() => {
    const { view } = appStore.app;
    const path = view.currentPath;

    let title = '';
    if (document && view.title) {
      title = view.title || document?.title;
    }
    window?.history.pushState(null, title, path);
  });
}
