import { isObject, isString, isValidFiniteNumber, makeFixer } from './utils';

export type InputSpec = {
  id: string;
  label: string;
  channel: number;
};

export const fixInputSpecLabel = makeFixer(isString, '[Unknown Input]');
export const fixInputSpecChannel = makeFixer(isValidFiniteNumber, 0);

export default function fixInputSpec(inputSpec: unknown): InputSpec | null {
  if (inputSpec === null) {
    return null;
  }

  if (!isObject(inputSpec)) {
    return null;
  }

  const i = inputSpec as {
    id: unknown;
    label: unknown;
    channel: unknown;
  };

  // Validate that we have both id and label
  if (!isString(i.id)) {
    return null;
  }

  i.label = fixInputSpecLabel(i.label);
  i.channel = fixInputSpecChannel(i.channel);

  return inputSpec as InputSpec;
}
