import { flattenToObject } from './component';

export function fixMissingComponents(components: any[], layers: any[]) {
  const layersById = flattenToObject(layers);
  return components.filter((d) => layersById[d.id] || d.parent);
}

export const fixPanelMissingComponents = (panelConfig) => {
  return panelConfig.map((d) => ({
    ...d,
    stateConfig: d.stateConfig.map((v) => ({
      ...v,
      componentsConfig: fixMissingComponents(v.componentsConfig, JSON.parse(v.screenConfig.layers || '[]')),
      panelConfig: fixPanelMissingComponents(v.panelConfig)
    }))
  }));
};
