import * as formsSelector from '@/modules/forms/forms/redux/selectors';

export const getTemplates = (state$) => {
  const templates = formsSelector.templatesSelector(state$);

  if (!templates.length) return [];

  const groupedByCategory = templates.reduce((acc, value) => {
    const existCategoryIndex = acc.findIndex((o) => o.formTemplateCategoryId === value.formTemplateCategory.id);

    if (existCategoryIndex === -1) {
      acc.push({
        formTemplateCategoryId: value.formTemplateCategory.id,
        formTemplateCategoryName: value.formTemplateCategory.name,
        records: [value],
      });
    } else {
      acc[existCategoryIndex] = {
        ...acc[existCategoryIndex],
        records: [].concat(acc[existCategoryIndex].records, value),
      };
    }

    return acc;
  }, []);

  return groupedByCategory;
};

export default {};
