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 {hides = []} = data;

    const [isActive, setIsActive] = useState(false);
    const [hideSelector, setHideSelector] = useState('');

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

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

    const isMounted = useMounted();

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

        const newHides = [...hides];
        if (hideSelector) {
            newHides.push(hideSelector);

            const newData = {...data, hides: newHides};
            setData(newData);

            if (draculaDarkMode.isEnabled()) {
                draculaDarkMode.disable();
                draculaDarkMode.enable(getConfig(newData));
            }
        }
    }, [hideSelector]);

    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>
    )
}