const captureBtn = document.querySelector('#capture');
const captureVideo = document.querySelector('#capture-video');
const captureContainer = document.querySelector('#capture-video-container');
const captureSelection = document.querySelector('#capture-selection')

async function captureStart() {
    try {
        captureContainer.style.display = 'inline-block';
        const displayMediaOptions = {
            audio:false,
            video:true,
            cursor: 'always',
            selfBrowserSurface: "exclude",
            surfaceSwitching: "include",
            monitorTypeSurfaces: "include",
        };
        navigator.mediaDevices.getDisplayMedia(displayMediaOptions).then((captureStream) => {
            fullscreen()
            captureVideo.srcObject = captureStream;
            selectionMount();

        });


    } catch(err) {
        captureStop();
        console.log(err)
    }
}


function isFullScreen() {
    return !!document.fullscreenElement;
}

function fullscreen() {
    if(isFullScreen()) {
        if(document.exitFullscreen) {
            document.exitFullscreen();
        }
    } else {
        if(document.documentElement.requestFullscreen) {
            document.documentElement.requestFullscreen();
        }
    }
}

function captureStop() {
    if (captureVideo.srcObject) {
        const tracks = captureVideo.srcObject.getTracks();
        tracks.forEach((t) => t.stop());
        captureVideo.srcObject = null;
    }
    captureContainer.style.display = 'none';

    fullscreen()
    selectionUnmount();
}

async function takeSnapshot() {

    const canvas = document.createElement('canvas');
    const context = canvas.getContext("2d");

    const rect = captureSelection.getBoundingClientRect();
    const videoRect = captureVideo.getBoundingClientRect();

    const scaleX = captureVideo.videoWidth / videoRect.width;
    const scaleY = captureVideo.videoHeight / videoRect.height;

    canvas.width = rect.width * scaleX
    canvas.height = rect.height * scaleY
    context.drawImage(
        captureVideo,
        (rect.left - videoRect.left) * scaleX,
        (rect.top - videoRect.top) * scaleY,
        rect.width * scaleX,
        rect.height * scaleY,
        0,
        0,
        canvas.width,
        canvas.height
    )
    const snapshot = canvas.toDataURL("image/png")
    console.log(snapshot)
}


captureVideo.addEventListener('playing', function() {
    captureVideo.pause()
})

function selectionMount() {
    let isSelection = false;
    let endX = 0;
    let endY = 0;
    let startX = 0;
    let startY = 0;


     const mouseDownListener = (e) => {
        startX = e.offsetX;
        startY = e.offsetY;
        isSelection = true;
        captureSelection.style.left = `${startX}px`;
        captureSelection.style.top = `${startY}px`;
        captureSelection.style.width = '0px';
        captureSelection.style.height = '0px';
        captureSelection.style.display = 'block';
    };

     const mouseMoveListener = (e) => {
        if (isSelection) {
            endX = e.offsetX;
            endY = e.offsetY;

            captureSelection.style.left = `${Math.min(startX, endX)}px`;
            captureSelection.style.top = `${Math.min(startY, endY)}px`;
            captureSelection.style.width = `${Math.abs(endX - startX)}px`;
            captureSelection.style.height = `${Math.abs(endY - startY)}px`;
        }
    };

    const mouseUpListener = (e) => {
        isSelection = false;
        takeSnapshot();
        captureStop();
    };

    captureVideo.removeEventListener('mousedown', mouseDownListener);
    captureVideo.removeEventListener('mousemove', mouseMoveListener);
    captureVideo.removeEventListener('mouseup', mouseUpListener);

    captureVideo.addEventListener('mousedown', mouseDownListener);
    captureVideo.addEventListener('mousemove', mouseMoveListener);
    captureVideo.addEventListener('mouseup', mouseUpListener);
}

function selectionUnmount() {
    captureSelection.style.left = `0px`;
    captureSelection.style.top = `0px`;
    captureSelection.style.width = '0px';
    captureSelection.style.height = '0px';
    captureSelection.style.display = 'none';
}

captureBtn.addEventListener('click', captureStart)