import {useEffect} from "react";
import SoundHelp from "@utils/SoundManger";
const buttonCache={

}
const useGlobalClick = () => {
    const checkIsButton=(target)=>{
        let tagName=target.tagName.toLowerCase();
        let className=target.getAttribute("class");
        if (buttonCache[className]!=null){
            return buttonCache[className];
        }
        if (tagName==="button"||tagName==="a"){
            if (className!=null){
                buttonCache[className]=target;
            }
            return target;
        }
        let buttons=document.getElementsByTagName("button");
        let alist=document.getElementsByTagName("a");
        let checkList=[buttons,alist];
        if (checkList){
            for (let i = 0; i < checkList.length; i++) {
                let btns=checkList[i];
                if (btns){
                    for (let j = 0; j < btns.length; j++) {
                        let button=btns[j];
                        if (button.contains(target)){
                            if (className!=null){
                                buttonCache[className]=button;
                            }
                            return button;
                        }
                    }
                }
            }
        }

        return null;
    }
    const onHandleClick=(e)=>{
        let button=checkIsButton(e.target);
        if (button){
            let clickAudio=button.getAttribute("clickAudio");
            if (clickAudio===false)return;
            SoundHelp.playSound("button_click");
        }
    }
    useEffect(()=>{
        document.addEventListener("click",onHandleClick,true);
        return ()=>{
            document.removeEventListener("click",onHandleClick,true);
        }
    },[])
    return {}
}
export default useGlobalClick;