import { IGenericSection } from '../../../../generic/types';

import { getMethods, methods } from '../methods';

function transformSection({ props, children }: IGenericSection) {
  // TODO : implement section subtypes 
  // const subtype = props?.subtype;
  const subtype = props?.slack?.type;
  if (subtype && subtype !== 'section' && methods[subtype]) {
    return getMethods(subtype)({ type: subtype, props, children });
  }

  const groupedElements = {};
  const groupedTypes = ['card', 'button'];
  let sections = [];
  let i = 0;
  while (i < children.length) {
    const item = children[i];
    if (groupedTypes.includes(item.type)) {
      groupedElements[item.type] = [item];
      i = i + 1;
      let next = children[i];
      while (next && next.type === item.type) {
        groupedElements[item.type].push(next);
        i = i + 1;
        next = children[i];
      }

      const type = item.type === 'button' ? 'buttonList' : 'carousel';
      const converted = getMethods(type)({ children: groupedElements[item.type] });
      sections = sections.concat(converted);
      groupedElements[item.type] = null;

      i = i - 1; // handle next element in the next outer iteration
    } else {
      const converted = getMethods(item.type)(item);
      sections = sections.concat(converted);
    }
    i = i + 1;
  }
  
  return sections.reduce((acc, item) => {
    if (acc.length === 0) {
      return [item];
    } else {
      const previous = acc[acc.length-1];
      if (previous.answerComponent) {
        if (item.medias && previous.answerComponent.allowMedia && !previous.medias?.length) {
          previous.medias = item.medias;
          return acc;
        } else {
          return acc.concat(item);
        }
      } else if (previous.message && item.message) {
        return acc.concat(item);
      } else {
        if (item?.message) {
          previous.message = item.message;
        }
        if (item?.answerComponent) {
          if (
            (!previous.message || item.answerComponent.sendMessage) &&
            (!previous.medias || previous.answerComponent.allowMedia)
          ) {
            previous.answerComponent = item.answerComponent;
          } else {
            delete item.message; // sanity deletion. message was handled in the 'if' above 
            return acc.concat(item);
          }
        }
        if (item.medias && !previous.medias?.length) {
          if (!previous.answerComponent || previous.answerComponent.allowMedia) {
            previous.medias = item.medias;
          } else {
            return acc.concat(item);
          }
        }
        return acc;
      }
    }
  }, []);
}

export {
  transformSection
};
