import uniqueId from 'lodash/uniqueId';
import { BaseOptionProps } from './types';

export function groupBy<TOption extends BaseOptionProps & { group?: string }>(option: TOption) {
  return option.group || option.componentType || 'other';
}

// TODO: should write the type better.
/**
 * @param {Record<string, T[]>} groupedOptions The object containing group names as keys and options as values
 * @returns Array of options with the group and id properties added
 */
export function makeOptionsArray<T extends BaseOptionProps>(groupedOptions?: Record<string, T[]>) {
  if (!groupedOptions) return;
  const options = [];
  function addGroupToOptions(groupName: string, options: T[]) {
    return options.map(opt => ({
      ...opt,
      group: opt.group || groupName,
      id: opt.id || uniqueId()
    }));
  }

  for (const [groupName, groupOptions] of Object.entries(groupedOptions)) {
    options.push(...addGroupToOptions(groupName, groupOptions));
  }

  return options;
}
