import { observer } from 'mobx-react';
import React from 'react';
import { NotFound } from '../templates/NotFound';
import { Route } from '../app/routing/route.interface';
import { IStoreWithBase } from './context.interface';
/**
 * 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
 */
export const AppViews: React.FC<{ store: IStoreWithBase<any> }> = observer(
  ({ store }) => {
    const { routes, path } = store;
    const params = store.app.view.params || {};

    const personalizedNotFoundPage = routes.filter(
      (route: 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) => route.path === path);

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