// @flow
import * as React from 'react';
import {
	Label, Input,
} from 'reactstrap';

import { expGetDefaultParameterValue as getDefaultParameterValue } from '@helpers/beat';
import type { ParameterValue } from '@helpers/beat';

type Props = {
	parameter: any,
	updateFunc: (ParameterValue) => any,
	currVal?: ParameterValue,
};

// given a parameter obj, its current value, and an update function,
// return an input for the specific type of parameter
const ParameterConsume = ({ parameter, updateFunc, currVal }: Props) => {
	if((parameter === null || parameter === undefined) || !parameter.hasOwnProperty('type'))
		return '';

	const parseVal = (v: ParameterValue): ParameterValue => {
		if(v === true || v === false)
			return v;
		if(parameter.type.includes('float'))
			return Number.parseFloat(`${ v }`);
		if(parameter.type.includes('int'))
			return Number.parseInt(`${ v }`);
		return v;
	};

	const pVal = currVal === undefined ? getDefaultParameterValue(parameter) : currVal;
	if(parameter.hasOwnProperty('choice'))
		return (
			<Input
				type='select'
				className='custom-select'
				value={pVal}
				onChange={e => updateFunc(parseVal(e.target.value))}
			>
				{ parameter.choice.map((c, i) => <option key={i} value={c}>{c}</option>) }
			</Input>
		);
	if(parameter.hasOwnProperty('range'))
		return (
			<Input
				type='number'
				min={parameter.range[0]}
				max={parameter.range[1]}
				value={pVal}
				onChange={e => updateFunc(parseVal(e.target.value))}
			/>
		);
	if(parameter.type === 'bool')
		return (
			<Label>
				<Input
					className='ml-0'
					type='checkbox'
					checked={pVal}
					onChange={e => updateFunc(parseVal(e.target.checked))}
				/>
			</Label>
		);
	if(parameter.type === 'string')
		return (
			<Input
				type='text'
				value={pVal}
				onChange={e => updateFunc(parseVal(e.target.value))}
			/>
		);
	else {
		const step = parameter.type.includes('float') ? 'any' : 1;
		return (
			<Input
				type='number'
				min={-1000000}
				max={1000000}
				step={step}
				value={pVal}
				onChange={e => updateFunc(parseVal(e.target.value))}
			/>
		);
	}
};

export default ParameterConsume;
