import { IGenericOptions, IGenericCheckbox } from "../../../generic/types";
import { IRWCAnswerComponent } from "../../types";
import { removeBackticks } from "../../utils";

const getDefaultValue = (options: Array<IGenericOptions>, def: Array<any>): Array<IGenericOptions> => {
  if (!def || !Array.isArray(def)) return null;

  const mappedDefValues = def.map(removeBackticks);

  const defaultValue = options.filter(option => mappedDefValues.includes(removeBackticks(option.label)));

  return defaultValue;
} ;

export const transformCheckboxGroup = (msg: IRWCAnswerComponent): IGenericCheckbox => {
  const options: Array<IGenericOptions> = msg.vBind?.options.map(({ label, value }) => {
    return {
      label,
      value,
      name: value,
      key: value
    };
  });

  
  const result: IGenericCheckbox = {
    type: 'checkbox',
    props: {
      value: {},
      options,
      multiple: true,
    }
  };
  
  const defaultValue = getDefaultValue(options, msg.vBind?.defaultValue);

  if (defaultValue) {
    options.forEach(({ name }) => {
      result.props.value[name] = defaultValue.findIndex(v => v.name === name) > -1;
    });
  }

  return result;
};
