/* eslint-disable react/prop-types */

import * as React from 'react';
import { useRaonkEditor } from 'raonkeditor-react';

const { useEffect, useState } = React;

/**
 * Custom `RaonkEditor` component built on top of `useRaonkEditor` hook.
 */
function RaonkEditor( { config, debug, mode, readOnly, runtimes, componentUrl, id } ) {
	const [ element, setElement ] = useState();

	/**
	 * Sets initial value of `readOnly`.
	 */
	 if ( config && readOnly ) {
		config.ReadOnly = readOnly;
	}

	/**
	 * Sets initial value of `readOnly`.
	 */
	if ( config && mode ) {
		config.Mode = mode;
	}

	const { component, status } = useRaonkEditor( {
		debug,
		element,
		config,
		componentUrl,
		runtimes
	} );

	/**
	 * Toggles `mode` on runtime.
	 */
	useEffect( () => {
		if ( component && status === 'ready' ) {
			( RAONKEDITOR.IsLoadedEditorEx(component.object.ID) ) && ( RAONKEDITOR.SetEditorMode(mode, component.object.ID) );
		}
	}, [ component, mode ] );

	/**
	 * Toggles `mode` on runtime.
	 */
	useEffect( () => {
		if ( component && status === 'ready' ) {
			( RAONKEDITOR.IsLoadedEditorEx(component.object.ID) ) && ( RAONKEDITOR.SetReadOnly(readOnly, component.object.ID) );
		}
	}, [ component, readOnly ] );

	return (
		<div
			id={id}
			ref={setElement}
		></div>
	);
}

export default RaonkEditor;
