import { createFieldWidget, createStaticWidget } from './widgetsMetadata';

const createStaticWidgets = (state) => {
  const widgets = [];
  const [LOGO, BANNER] = state.image;

  if (LOGO) {
    widgets.push(
      createStaticWidget.logo({
        src: LOGO,
        order: widgets.length + 1,
      }),
    );
  }

  if (BANNER) {
    widgets.push(
      createStaticWidget.banner({
        src: BANNER,
        order: widgets.length + 1,
      }),
    );
  }

  if (state.title) {
    widgets.push(
      createStaticWidget.title({
        text: state.title,
        order: widgets.length + 1,
      }),
    );
  }

  if (state.description) {
    widgets.push(
      createStaticWidget.description({
        text: state.description,
        order: widgets.length + 1,
      }),
    );
  }

  return widgets;
};

const createFieldWidgets = (state) => {
  const fields = [];

  state.dynamicFields.forEach((field, index) => {
    const createFieldJsonFn = createFieldWidget[field.component];

    if (createFieldJsonFn) {
      const fieldJson = createFieldJsonFn({
        ...field,
        order: index,
      });

      fields.push(fieldJson);
    }
  });

  return fields;
};

export const createFormMetadata = (state) => {
  const metadata = {
    globalConfig: {
      name: state.name,
      version: '1',
      styles: {
        bgColor: state.style.bgColor,
        alignment: state.style.alignItems,
        font: {
          family: state.style.fontFamily,
          size: state.style.fontSize,
          color: state.style.fontColor,
        },
      },
      links: {
        privacy: {
          title: state.privacyPolicy.title,
          src: state.privacyPolicy.src,
        },
        termsConditions: {
          isHidden: !state.termsConditions.isActive,
          title: state.termsConditions.title,
          src: state.termsConditions.src,
        },
      },
    },
    widget: {
      component: 'Container',
      props: [
        {
          columns: 12,
          order: 1,
          widget: {
            component: 'Container',
            props: createStaticWidgets(state),
          },
        },
        {
          columns: 12,
          order: 2,
          widget: {
            component: 'Form',
            props: {
              skipButton: {
                isHidden: !state.skipButton.isActive,
                title: state.skipButton.title,
                bgColor: '',
                textColor: state.style.submitButtonBgColor,
              },
              submitButton: {
                title: state.submitButton.title,
                bgColor: state.style.submitButtonBgColor,
                textColor: state.style.submitButtonFontColor,
              },
              fields: createFieldWidgets(state),
            },
          },
        },
      ],
    },
  };

  return metadata;
};
