import { ColumnType, MatchedOptions, MatchedSelectColumn, MatchedSelectOptionsColumn, MatchedMultiSelectColumn } from "../types"

export const setSubColumn = <T>(
  oldColumn: MatchedSelectColumn<T> | MatchedSelectOptionsColumn<T> | MatchedMultiSelectColumn<T>,
  entry: string,
  value: string,
): MatchedSelectColumn<T> | MatchedSelectOptionsColumn<T> | MatchedMultiSelectColumn<T> => {
  const options = oldColumn.matchedOptions.map((option) => (option.entry === entry ? { ...option, value } : option))
  const allMatched = options.every(({ value }) => !!value)

  if (oldColumn.type === ColumnType.matchedMultiSelect) {
    return { ...oldColumn, matchedOptions: options as MatchedOptions<T>[] }
  }
  
  if (allMatched) {
    return { ...oldColumn, matchedOptions: options as MatchedOptions<T>[], type: ColumnType.matchedSelectOptions }
  } else {
    return { ...oldColumn, matchedOptions: options as MatchedOptions<T>[], type: ColumnType.matchedSelect }
  }
}
