// @flow
import * as React from 'react';
import {
	Row,
	Col,
	Button,
	Form, FormGroup,
	Label, Input,
	Card, CardHeader, CardBody,
	TabContent, TabPane, Nav, NavItem, NavLink,
	Alert,
	UncontrolledDropdown, DropdownToggle, DropdownMenu,
	InputGroup, InputGroupAddon,
} from 'reactstrap';

import { connect } from 'react-redux';

import cn from 'classnames';

import { changeObjFieldName, generateNewKey, copyObj } from '@helpers';
import { BUILTIN_TYPES, ANALYZER_RESULT_TYPES, getValidPlotterparameterObj as getValidObj, expGetDefaultParameterValue as getDefaultParameterValue } from '@helpers/beat';
import type { BeatObject } from '@helpers/beat';

import * as Selectors from '@store/selectors.js';

import * as Actions from '@store/actions.js';
import CacheInput from '../CacheInput.jsx';
import ValidSchemaBadge from '../ValidSchemaBadge.jsx';
import DeleteInputBtn from '../DeleteInputBtn.jsx';
import TypedField from '../TypedField.jsx';
import TemplateButton from '../EntityTemplateGenerationButton.jsx';
import InfoTooltip from '../InfoTooltip.jsx';
import ParameterConsume from '../ParameterConsume.jsx';

type Props = {
	plotters: BeatObject[],
	data: BeatObject,
	saveFunc: (BeatObject) => any,
	updateFunc: (BeatObject) => any,
};

export class PlotterParameterEditor extends React.Component<Props> {
	constructor(props: Props) {
		//console.log(`Creating AlgDetail`);
		super(props);
	}

	setContents = (newContents: any) => {
		this.props.updateFunc({
			...this.props.data,
			contents: {
				...this.props.data.contents,
				...newContents,
			}
		});
	}

	updateDescription = (desc: string) => {
		this.setContents({ description: desc });
	}

	getPlotterName = (): string => {
		return this.props.data.contents.plotter;
	}

	getPlotter = (name: ?string) => {
		const n = name || this.getPlotterName();
		const pl = this.props.plotters.find(pl => pl.name === n);
		return pl || {};
	}

	updatePlotter = (plName: string) => {
		const pl = this.getPlotter(plName);
		const oldPlotter = this.getPlotterName();
		if(oldPlotter === pl.name)
			return;

		this.setContents({
			plotter: pl.name,
			data: Object.entries(pl.contents.parameters)
			.map(([p, info]) => ({ [p]: getDefaultParameterValue(info) }))
			.reduce((o, p) => ({ ...o, ...p }), {})
		});
	}

	updateParameter = (pName: string, v: number | string | boolean) => {
		this.setContents({
			data: {
				...this.props.data.contents.data,
				[pName]: v
			}
		});
	}

	render = () => {
		const pn = this.getPlotterName();
		const pl = this.getPlotter(pn);

		return (
			<div>
				<div className='d-flex'>
					<Button
						className='mx-auto'
						outline
						color='secondary'
						onClick={() => this.props.saveFunc(this.props.data)}
					>
						Save Changes (Changes are <ValidSchemaBadge entity='plotterparameter' obj={this.props.data} />)
					</Button>
					{/*
					<TemplateButton
						data={this.props.data}
						entity={'plotter'}
					/>
					*/}
				</div>
				<Form>
					<FormGroup tag='fieldset'>
						<FormGroup>
							<Label>Short Description</Label>
							<Input
								type='text'
								id='ppDesc'
								placeholder='Parameter description...'
								value={this.props.data.contents.description}
								onChange={(e) => this.updateDescription(e.target.value)}
							/>
						</FormGroup>
						<FormGroup>
							<Label>Plotter</Label>
							<Input
								type='select'
								className='custom-select'
								id='ppPl'
								placeholder='Plotter...'
								value={pn}
								onChange={e => this.updatePlotter(e.target.value)}
							>
								{
									this.props.plotters.map((pl, i) =>
										<option key={i} value={pl.name}>{ pl.name }</option>
									)
								}
							</Input>
						</FormGroup>
						<h5>Parameters</h5>
						{
							pl.contents &&
								Object.entries(pl.contents.parameters).map(([pName, o], i) =>
									<FormGroup row key={i}>
										<Label sm={4}>{ pName }</Label>
										<Col>
											<ParameterConsume
												parameter={o}
												updateFunc={(v: any) => this.updateParameter(pName, v)}
												currVal={this.props.data.contents.data[pName]}
											/>
										</Col>
									</FormGroup>
								)
						}
					</FormGroup>
				</Form>
			</div>
		);
	}
}

const mapStateToProps = (state, ownProps) => {
	const params = Selectors.plotterparameterGet(state);
	const obj = {
		plotters: Selectors.plotterGet(state),
		data: params[ownProps.index] || getValidObj(),
	};

	if(!obj.data.contents.hasOwnProperty('plotter') ||
		obj.data.contents.plotters === "")
	{
		obj.plotters.unshift({name: "-- select an option --"})
	};

	return obj;
};

const mapDispatchToProps = (dispatch, ownProps) => ({
	// replace the obj in the Redux store with the new object
	updateFunc: (obj) => {
		console.log(`dispatching for ${ obj.name }`);
		dispatch(Actions[`plotterparameterUpdate`](obj.name, obj));
	},
});

export default connect(mapStateToProps, mapDispatchToProps)(PlotterParameterEditor);
