import { IGenericOptions, IGenericGroupOptions } from '../../../../generic/types/utils/options';
import { ISlackOptionObject, ISlackOptionGroupObject } from '../../../types';
import { transformTextObject } from './transform-text-object';

function convertSingleOption(item): IGenericOptions {
  if (!item?.text && !item.value) return;
  
  // const textObject = transformText(item.text);
  const label = transformTextObject(item.text);

  const res: IGenericOptions = {
    key: item.value,
    value: item.value,
    name: item.value,
    label: label?.value || item.value,
    slack: label?.slack
  };

  if (item.description || item.url) {
    if (item.description) {
      res.slack.description = transformTextObject(item.description);
    }

    if (item.url) res.slack.url = item.url;
  }

  return res;
}

function convertOptions(arr: Array<ISlackOptionObject>): Array<IGenericOptions> {
  return arr.map(item => convertSingleOption(item));
}

function convertGroupOption(item) {
  return {
    label: transformTextObject(item.label),
    options: item.options.map(item => convertSingleOption(item))
  };
}

function convertGroupOptions(arr: Array<ISlackOptionGroupObject>): Array<IGenericGroupOptions> {
  const res: Array<IGenericGroupOptions> = [];

  for (let i = 0; i < arr.length; i++) {
    const item: ISlackOptionGroupObject = arr[i];
    res.push(convertGroupOption(item));
  }

  return res;
}

export {
  convertOptions,
  convertSingleOption,
  convertGroupOption,
  convertGroupOptions
};