
import { useEffect, useMemo, useRef } from "preact/hooks";
import ace from "ace-builds";
import { useIsVisible } from "@common/hooks/useIsVisible";

import "ace-builds/src-noconflict/mode-django";
import "ace-builds/src-noconflict/theme-terminal";

interface IAceProps {
    value: string;
    onInput: (e: InputEvent | string) => void;
}

export const Ace = ({ value, onInput }: IAceProps) => {
    const ref = useRef<HTMLDivElement>(null);
    const isVisible = useIsVisible(ref);

    const editor = useMemo(() => {
        if (ref.current) {
            const e = ace.edit(ref.current, {
                theme: 'ace/theme/terminal',
                mode: 'ace/mode/django',
                showGutter: false,
                showPrintMargin: false,
                highlightActiveLine: false,
                displayIndentGuides: false,
                fontSize: 16,
                maxLines: Infinity,
                tabSize: 2,
                useSoftTabs: true,
                wrap: "free",
            });
            return e;
        }
    }, [isVisible]);

    useEffect(() => {
        if (editor) {
            if (editor.getValue() !== value) {
                const pos = editor.getCursorPosition();
                editor.setValue(value);
                editor.selection.clearSelection();
                editor.moveCursorToPosition(pos);
            }
        }
    }, [editor, value]);

    useEffect(() => {
        if (onInput && editor) {
            const e = editor;
            const handler = () => onInput(e.getValue());

            e.on('input', handler);
            return () => e.off('input', handler);
        }
    }, [editor, onInput]);

    return (
        <div ref={ref} />
    );
}