import React,{useEffect,useRef} from 'react';
import modalImpl from './Modal.NestedImplementation';

export default function Modal(props) {
   
    // Create a div that we'll render the modal into. Because each
    // Modal component has its own element, we can render multiple
    // modal components into the modal container.

   
    let wrapperObjForFloatingUI = document.createElement('div');
    wrapperObjForFloatingUI.className = 'floatingcontainer_' + new Date().getTime();
    
   
    useEffect( ()=>{
        props.modalrootNode.appendChild(wrapperObjForFloatingUI);
        const modalObj = Object.assign({}, props, {wrapperObjForFloatingUI:wrapperObjForFloatingUI,UID:wrapperObjForFloatingUI.className});
        modalImpl.init(modalObj);
        modalImpl.persistFloatingUIInfoInList();
        modalImpl.applyFocusToFloatingDialogElement();
        modalImpl.persistPageElementReference();
        modalImpl.bindKeyDownEventToDocument();
        return function cleanUp()
            {
                let indexOfContainerElement = modalImpl.getIndexOfContainerElement(
                    wrapperObjForFloatingUI.className
                  );
                  modalImpl.removeFloatingUIContainerElement(
                    indexOfContainerElement,
                    wrapperObjForFloatingUI.className
                  );  
            }
      
    },[props]);

  let skeletonOfModal = <>
  
    {props.freezeLayer ? 
    props.freezeLayer(props)
    :props.children
  }
    </>
  return ReactDOM.createPortal(
    // Any valid React child: JSX, strings, arrays, etc.
    skeletonOfModal,
    // A DOM element
    wrapperObjForFloatingUI
  );
  
}



