import * as React from 'react';
import { DEXT5Editor } from 'dext5editor-react';
import Sidebar from './Sidebar';

const { version, useReducer } = React;

/**
 * `App` component manages state of underlying `DEXT5Editor` and `Sidebar` components.
 */
function App() {
	const [ { config, readOnly, id }, dispatch ] =
		useReducer( reducer, {
			config: getConfig(),
			readOnly: false,
			id: getUniqueName()
	} );

	const handleReadOnlyChange = evt => {
		const checked = evt.currentTarget.checked;
		dispatch( { type: 'readOnly', payload: checked } );
	};

	return (
		<div>
			<section className="container">
				<Sidebar
					readOnly={readOnly}
					onReadOnlyChange={handleReadOnlyChange}
				/>
				<div className="paper flex-grow-3">
					<DEXT5Editor
						key={id}
						
						debug={true}
						id={id}
						config={config}
						initData="<p>Hello <strong>DEXT5 Editor</strong> world!</p>"
						readOnly={readOnly}
						componentUrl="/dext5editor/js/dext5editor.js"
					/>
				</div>
			</section>
			<footer>{`Running React v${ version }`}</footer>
		</div>
	);
}

function reducer( state, action ) {
	switch ( action.type ) {
		case 'readOnly':
			return {
				...state,
				readOnly: action.payload
			};
		default:
			return state;
	}
}

function getConfig( ) {
	return {
		...{ Mode: "edit", SkinName: "blue" }
	};
}

function getUniqueName() {
	return Math.random()
		.toString( 36 )
		.replace( /[^a-z]+/g, '' )
		.substr( 0, 5 );
}

export default App;
