import "systemjs/dist/system";
import "systemjs/dist/extras/amd";
import "systemjs/dist/extras/named-register";
import "systemjs/dist/extras/named-exports";
import "systemjs/dist/extras/transform";
import { createBrowserHistory } from 'history'
import { Apps } from './apps'
import { defineVirtualModule } from './virtual-module'

const systemJSImport = async (requestUrl: string) => {
  const { default: component, mount, unmount } = await System.import(
    requestUrl
  )
  return { component, mount, unmount }
}

// const defaultNavigations = {
//   login: '/login',
//   main: '/main',
//   news: '/news',
//   org: '/org',
//   sections: '/sections',
//   'news.details': '/news/{{id}}',
//   'org.details': '/org/{{name}}',
//   'sections.details': '/sections/{{name}}'
// }

// const defaultApps = {
//   login: { version: '1.0.0', name: 'login' },
//   main: { version: '1.0.1', name: 'main' },
//   news: { version: '1.0.0', name: 'news' },
//   org: { version: '1.0.0', name: 'org' },
//   sections: { version: '1.0.0', name: 'sections' }
// }

export default async ({ apps: rawApps, navigations, config, features }) => {
  defineVirtualModule({ navigations, config, features })

  const apps = new Apps(rawApps)

  const history = createBrowserHistory()

  let prevPathname = window.location.pathname

  const app = apps.findApp(history.location.pathname)

  const publicPath = `/${app.name}/${app.version}`

  __webpack_public_path__ = `${config.baseUrl}${publicPath}${__webpack_public_path__}`

  const appPath = `${config.baseUrl}${publicPath}/index.js`

  const { component, mount, unmount } = await systemJSImport(appPath);

  mount(component.default);

  history.listen((location) => {
    if (location.pathname !== prevPathname) {
      prevPathname = location.pathname
      unmount()
    }
  })
};