import { IGenericFields, IGenericHeader, IGenericLink, IGenericSection } from '../../../generic/types';
import { IOutputCard } from '../../types';
import { transformText } from './text';

const convertCard = message => {
  const fieldsSection: IGenericFields = {
    type: 'fields',
    props: {
      column: 2
    },
    children: []
  };

  const data = JSON.parse(message.data);
  const title = data.title ? `${data.title}` : '';
  const subtitle = data.subtitle ? `${data.subtitle}` : '';

  const headerElements = [];
  
  if (data.url) {
    const link: IGenericLink = {
      type: 'link',
      props: {
        url: data.url
      },
      children: []
    };
    if (subtitle) {
      link.children.push(transformText(subtitle));
      headerElements.push(transformText(title));
      headerElements.push(link);
    } else {
      link.children.push(transformText(title));
      headerElements.push(link);
      headerElements.push(transformText(subtitle));
    }
  }

  const header = headerElements.map(item => {
    const element: IGenericHeader = {
      type: 'header',
      props: {
        level: 3
      },
      children: [item]
    };
    return element;
  });

  fieldsSection.children.push(...header);

  if (data?.fields?.length > 0) {
    data.fields.forEach(field => {
      const label = `**${field.fieldLabel || ''}**`; // make label bold
      const value = field.fieldValue;

      fieldsSection.children.push(transformText(label, 'markdown'), transformText(value));
    });
  }
  
  return fieldsSection;
};

export const transformOutputCard = (msg: IOutputCard): IGenericSection => {
  const result: IGenericSection = {
    type: 'section',
    children: [].concat(convertCard(msg))
  };

  return result;
};
