import React,{ useEffect, useCallback } from "react";
import focusScope from "./focusScopeUtil";

/**
 * Automatically start autofocus the focusable first element once mounted within the container(elementRef) and 
 * Also create inside focus looping the container(elementRef)
 * Also we do restore focus for popup and Modal scenarios  
 * Example : use
function Component(props){

    let elemenetRef = React.createRef();

    useFocusScope({ autoFocus: true , focusLoop: false, elemenetRef });

    return <div ref={elemenetRef}>

            <input /> <!-- default focusable tags   -->
            <button /> <!-- default focusable tags  -->
            <div data-aria-focus tabindex /> <!-- create own focusable tag with focus options  -->
    </div>

}
 * By default all (autoFocus, focusLoop, restoreFocus) will be false.
 * param - autoFocus , focusLoop, restoreFocus, ref
 * return void 
 */
export default ({ autoFocus=false , focusLoop=false, restoreFocus=false, getElementRef=null, restoreFocusId='1', isNested=false })=>{

    /*let getElementRef =()=>{
        return elementRef && elementRef.current || null;
    };*/

    useEffect(()=>{
               
        let elemenetRef = getElementRef && getElementRef();
        autoFocus && focusScope.autoFocus(elemenetRef, autoFocus);
        focusLoop && focusScope.focusLoop(elemenetRef, focusLoop);
        restoreFocus && focusScope.restoreFocus(restoreFocus,restoreFocusId, isNested);

        return ()=>{
            focusScope.focusLoop(elemenetRef, false);
            focusScope.restoreFocus(false,restoreFocusId, isNested);
        }

    },[]);  // Didmount , un-mount


    useEffect(()=>{

        let elemenetRef = getElementRef && getElementRef();
        focusScope.autoFocus(elemenetRef, autoFocus);

    },[autoFocus]); // didUpdate when updatinge the component by api.

    useEffect(()=>{

        let elemenetRef = getElementRef && getElementRef();
        focusScope.focusLoop(elemenetRef, focusLoop);

    },[focusLoop]); // didUpdate when updatinge the component by api.

}