import React, { memo, useContext } from 'react';
import ComponentWrap from './ComponentWrap';
import GroupWrap from './GroupWrap';
import PanelWrap from './PanelWrap';
import { componentOperator } from 'utils/component';
import { ScreenContext } from './Screen';
import { isGeneralPanel } from 'utils/utils';
import { connect } from 'react-redux';
import { componentDataSyanc } from 'models/component';
import { getId } from 'utils/interaction';

function Components({ layers, edit, parentScreens, screenId, show = true, componentDataSyanc }) {
  const focusSet = useContext(ScreenContext);
  const focusStatus = !!focusSet;

  return layers
    .concat()
    .reverse()
    .map((d) => {
      const { id } = d;
      if (componentOperator.isGroup(id)) {
        return (
          <GroupWrap
            key={id}
            edit={edit}
            {...d}
            show={show && d.show}
            hasFocus={focusStatus}
            parentScreens={parentScreens}
            screenId={screenId}
          />
        );
      } else {
        if (focusSet && !focusSet.has(id)) return null;
        if (isGeneralPanel(id)) {
          const panelId = getId(id) as number;
          panelId && componentDataSyanc(panelId);
          return <PanelWrap key={id} edit={edit} {...d} show={show && d.show} parentScreens={parentScreens} screenId={screenId} />;
        }
        componentDataSyanc(id);
        return <ComponentWrap key={id} edit={edit} {...d} show={show && d.show} />;
      }
    });
}

export default connect(undefined, {
  componentDataSyanc
})(memo(Components));
