import React, { useContext, useEffect } from 'react';
import { ScreenContext, PanelDataContext, InteractionContext } from './Context';
import Panel from './Panel';
import { getState, getId } from 'utils/interaction';

interface PanelWrapProps {
  id: string;
}

function PanelWrap({ id }: PanelWrapProps) {
  const { switchPanelState, getPanelData } = useContext(ScreenContext);
  const { panelsById = {} } = useContext(PanelDataContext);
  const { interactions = [] } = useContext(InteractionContext);
  const panelId = getId(id) as number;

  const panel = panelsById[panelId];

  useEffect(() => {
    if (!panel) {
      getPanelData && getPanelData(panelId);
    }
  }, [panelId]);

  if (panel) {
    const { config = {}, states = [], screenConfig = [] } = panel;
    const { iState, iActiveState } = getState({ id, interactions });

    return (
      <Panel
        id={id}
        states={states}
        config={config}
        iState={iState}
        iActiveState={iActiveState}
        screenConfig={screenConfig}
        switchPanelState={switchPanelState}
      />
    );
  } else {
    return null;
  }
}

export default PanelWrap;
