import { WidgetTypes, Widget } from 'src/types/widgets';

const isWidget = (value: unknown): value is Widget =>
  typeof value === 'object' &&
  value !== null &&
  'type' in value &&
  'active' in value;

const normalizeWidgets = (widgets: unknown): Widget[] => {
  if (!Array.isArray(widgets)) {
    return [];
  }

  return widgets.filter(isWidget);
};

export const getActiveUrls = (widgets?: unknown) =>
  normalizeWidgets(widgets).filter(
    widget => widget.type === WidgetTypes.URL && widget.active,
  );

export const getActiveLibraries = (widgets?: unknown) =>
  normalizeWidgets(widgets).filter(
    widget => widget.type === WidgetTypes.KNOWLEDGE_LIBRARY && widget.active,
  );
