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

const {useState, useRef} = React;

export default function SelectElement({data, setData, index}) {
    const {toggleTriggers = []} = data;

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

    const updateSelector = (selector) => {

        setData({
            ...data,
            toggleTriggers: [...toggleTriggers.slice(0, index), {...toggleTriggers[index], 'selector': selector}, ...toggleTriggers.slice(index + 1)]
        });

    }

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

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

    return (
        <button
            type={`button`} className={`dracula-btn select-element ${isActive ? 'active' : ''} input-group-append`}
            onClick={() => {
                if (isActive) {
                    setIsActive(false);
                    DomeOutlineRef.current.stop();
                } else {
                    setIsActive(true);
                    DomeOutlineRef.current.start();
                }
            }}>
            {isActive ?
                <span className="dashicons dashicons-no-alt"/>
                :
                <span className="dracula-btn-icon icon-select-elements"></span>
            }
        </button>
    )
}