// @flow
import React from 'react';
import {
	Button,
	Form, FormGroup, Label, Input,
	Modal, ModalHeader, ModalBody, ModalFooter,
} from 'reactstrap';

import { connect } from 'react-redux';
import * as Actions from '@store/actions.js';

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

import { genModuleApiFuncs } from '@helpers/api';
import type { BeatSettings } from '@helpers/beat';

type Props = {
	isOpen: boolean,
	toggle: () => mixed,
	settings: BeatSettings,
	updateSettings: (obj: BeatSettings) => any,
	fetchAllObjects: () => any,
};

export class Settings extends React.PureComponent<Props> {
	constructor(props: Props){
		super(props);
	}

	save = async () => {
		await genModuleApiFuncs('settings').put(this.props.settings);
		await this.props.fetchAllObjects();
	}

	render = () => {
		const {isOpen, toggle, settings} = this.props;
		return (
			<Modal isOpen={isOpen} toggle={toggle} autoFocus={true}>
				<ModalHeader toggle={toggle}>Settings</ModalHeader>
				<ModalBody>
					<Form>
						{
							Object.entries(settings).map(([name, val], i) =>
								<FormGroup key={i}>
									<Label>{ name }</Label>
									<Input
										autoFocus
										value={val}
										onChange={e => {
											this.props.updateSettings({
												...settings,
												[name]: e.target.value,
											});
										}}
									/>
								</FormGroup>
							)
						}
					</Form>
					<a href='https://gitlab.idiap.ch/jdiefenbaugh/beat.editor'>Github</a>
				</ModalBody>
				<ModalFooter>
					<Button color="primary" onClick={this.save}>Write Settings to server</Button>
					<Button color="secondary" onClick={toggle}>Close</Button>
				</ModalFooter>
			</Modal>
		);
	}
}

const mapStateToProps = state => ({
	settings: Selectors.settingsGet(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
	updateSettings: (obj) => {
		dispatch(Actions.settingsUpdate(obj));
	},
	fetchAllObjects: () => {
		dispatch(Actions.fetchAllObjects());
	},
});

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