import { 
  IGenericHeader, 
  IGenericLink, 
  IGenericSection, 
  IGenericFields, 
  IGenericContext
} from '../../../generic/types';
import { 
  IGroupedPartsOutputControl, 
  IPartOutputControl,
} from '../../types';

import { transformText } from './text';

export const transformGroupedPartControl = (msg: IGroupedPartsOutputControl) => {
  const result: Array<IGenericSection|IGenericFields> = [];

  if (msg.header) {
    const textSection: IGenericSection = {
      type: 'section',
      children: [transformText(msg.header)]
    };
    result.push(textSection);
  }

  if (msg.groupPartType === 'Link') {
    const links: Array<IGenericFields> = msg.values
      .map((item: IPartOutputControl) => {       
        const label = item.label || '';
        const description = item.description || '';
        const context = item.context || '';
        
        const link: IGenericLink = {
          type: 'link',
          props: {
            url: item.action
          },
          children: [transformText(label)]
        };
        
        const header: IGenericHeader = {
          type: 'header',
          children: [link]
        };

        const ctxSection: IGenericContext = {
          type: 'context',
          children: [transformText(context)]
        };

        const groupedSection: IGenericFields = {
          type: 'fields',
          props: { column: 1 },
          children: [
            header, 
            transformText(description), 
            ctxSection
          ]
        };

        return groupedSection;
      }); 
    
    result.push({
      type: 'fields',
      props: { column: 1 },
      children: links
    });
  }

  return result;
};