import unique from "unique-selector";
import DomOutline from "./DomOutline";
import {getConfig, useMounted} from "../../includes/functions";

const {useState, useEffect, useRef} = React;

export default function SelectElements({data, setData}) {
    const {excludes = []} = data;

    const [isActive, setIsActive] = useState(false);
    const [excludeSelector, setExcludeSelector] = useState('');

    const DomeOutlineRef = useRef(DomOutline({
        onClick: (event, element) => {
            setIsActive(false);
            const selector = unique(element, {selectorTypes: ["ID", "Class", "Tag", "NthChild"]});

            if (selector) {
                setExcludeSelector(selector);
            }
        },
    }));

    const isMounted = useMounted();

    useEffect(() => {
        if (!isMounted) return;

        const newExcludes = [...excludes];

        if (excludeSelector) {
            newExcludes.push(excludeSelector);

            const newData = {...data, excludes: newExcludes};
            setData(newData);

            if (draculaDarkMode.isEnabled()) {
                draculaDarkMode.disable();
                draculaDarkMode.enable(getConfig(newData));
            }
        }

    }, [excludeSelector]);

    return (
        <button
            type={`button`} className={`dracula-btn select-elements ${isActive ? 'active' : ''}`}
            onClick={() => {
                if (isActive) {
                    setIsActive(false);
                    DomeOutlineRef.current.stop();
                } else {
                    setIsActive(true);
                    DomeOutlineRef.current.start();
                }
            }}>
            <span className="dracula-btn-icon icon-select-elements"></span>
            <span>{isActive ? 'Cancel Selection' : 'Select Element'}</span>
        </button>
    )
}