import { observer } from 'mobx-react';
import React from 'react';
import { useApphouse } from '../context/useApphouse';
import { NotFound } from '../templates/NotFound';
import { omit } from '../utils/obj/omit';
/**
 * This component is responsible for rendering all views
 * that are currently active in the app.
 * The views that are specified in the routes are rendered
 */
const Views: React.FC = observer(() => {
  const store = useApphouse();
  const { routes } = store;
  const params = store.app.view.params || {};
  console.log('params', params);

  const pathParams = omit(params, ['path']);
  const path = params.path || '/404';

  console.log('path', path, pathParams);
  const personalizedNotFoundPage = routes.filter(
    (route) => route.path === '/404'
  );

  if (path === '/404') {
    if (personalizedNotFoundPage.length > 0) {
      // Return personalized Not Found Page
      const component = personalizedNotFoundPage[0].component(params);
      return <component.type key={component.key} {...component.props} />;
    }
    // Return Apphouse's default Not Found Page
    return <NotFound />;
  }

  const activeViews = routes.filter((route) => route.path === path);

  return (
    <>
      {activeViews.map((route) => {
        if (route.path === path) {
          const component = route.component(params);
          if (!component) {
            return null;
          }
          return <component.type key={component.key} {...component.props} />;
        }
        return null;
      })}
    </>
  );
});

export default Views;
