import {useContext, useRef, useState} from "react";
import {PopContext} from "../../dataCenter/Root";
import closeIcon from '../../static/closeIcon.svg'

function PopContainer(props) {
    const dragRef = useRef()
    const {hidePop} = useContext(PopContext)
    const [offset, setOffset] = useState({x: 0, y: 0})
    const [draggable, setDraggable] = useState(false)
    const handleMouseDown = e => {
        e.stopPropagation()
        setDraggable(true)
        setOffset({
            x: e.clientX - dragRef.current['getBoundingClientRect']().x,
            y: e.clientY - dragRef.current['getBoundingClientRect']().y
        })
    }

    const handleMouseUp = () => setDraggable(false)
    const handleMouseMove = e => {
        if (draggable) {
            let x = e.clientX - offset.x
            let y = e.clientY - offset.y
            // console.log(x, y)
            if (x < 0) x = 0
            if (y < 0) y = 0
            if (x + dragRef.current['offsetWidth'] > document.body.offsetWidth) x = document.body.offsetWidth - dragRef.current['offsetWidth']
            if (y + dragRef.current['offsetHeight'] > document.body.offsetHeight) y = document.body.offsetHeight - dragRef.current['offsetHeight']
            dragRef.current.style.transform = `translate(${x}px,${y}px)`
        }
    }
    return (
        <div className="drag-Container"
             onMouseUp={() => handleMouseUp()}
             onMouseMove={(e) => handleMouseMove(e)}>
            <div className="Pop-container"
                 ref={dragRef}
            >
                <div className="Pop-tool" onMouseDown={e => handleMouseDown(e)}>
                    <button className="close" onClick={() => hidePop()}><img src={closeIcon} alt=''/></button>
                </div>
                {props.children}
            </div>
        </div>
    )
}

export default PopContainer
