// @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 { 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,
};

type State = {
	defaults: {[string]: any},
};

// generate the default plotterparameter for a given plotter
// return empty if the given plotter is empty
const getDefaultsParameter = (plotter: any): {[string]: any} => {
	if(Object.entries(plotter).length === 0){
		return {};
	}

	return Object.entries(plotter.contents.parameters)
	.map(([p, info]) => ({ [p]: getDefaultParameterValue(info) }))
	.reduce((o, p) => ({ ...o, ...p }), {});
};

export class PlotterParameterEditor extends React.Component<Props, State> {
	constructor(props: Props) {
		//console.log(`Creating AlgDetail`);
		super(props);
		this.state = {
			// calculate the defaults for the pp
			defaults: getDefaultsParameter(this.getPlotter()),
		};
	}

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

	// provide custom save func -
	// don't save default properties to plotterparmaeter!
	// only save properties with values that arent
	// equal to the default value.
	saveParameter = () => {
		const pl = this.getPlotter();
		const defaults = this.state.defaults;
		const curr = this.props.data.contents.data;
		const diff = Object.entries(defaults)
		// only save fields that arent the default value
		.filter(([field, dval]) => curr.hasOwnProperty(field) && dval !== curr[field])
		.map(([field, dval]) => [field, curr[field]])
		.reduce((o, [field, val]) => ({...o, [field]: val}), {})
		;

		const paramToSave = copyObj(this.props.data);
		paramToSave.contents.data = diff;
		this.props.saveFunc(paramToSave);
	}

	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: {}
		});

		this.setState({
			defaults: getDefaultsParameter(pl),
		});
	}

	// update the value of a parameter
	updateParameter = (pName: string, v: number | string | boolean) => {
		const newData = copyObj(this.props.data.contents.data);
		// if the new value is equal to the default value,
		// dont save the field
		// else update the field value
		if(v === this.state.defaults[pName]){
			delete newData[pName];
		} else {
			newData[pName] = v;
		}

		this.setContents({
			data: newData
		});
	}

	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.saveParameter()}
					>
						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);
