'use strict';

const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const photo = document.getElementById('photo');
const startbutton = document.getElementById('startbutton');

function startVideo() {
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
        .then(function(stream) {
            video.srcObject = stream;
            video.play();
        })
        .catch(function(err) {
            console.log("An error occurred: " + err);
        });
}

function takepicture() {
    const context = canvas.getContext('2d');
    if (width && height) {
        canvas.width = width;
        canvas.height = height;
        context.drawImage(video, 0, 0, width, height);

        const data = canvas.toDataURL('image/png');
        photo.setAttribute('src', data);

        // Copiar la imagen al portapapeles
        canvas.toBlob(function(blob) {
            const item = new ClipboardItem({ "image/png": blob });
            navigator.clipboard.write([item]).then(function() {
                alert("Imagen copiada al portapapeles");
            }, function(err) {
                console.error("Error al copiar la imagen al portapapeles: ", err);
            });
        });
    } else {
        clearphoto();
    }
}

function clearphoto() {
    const context = canvas.getContext('2d');
    context.fillStyle = "#AAA";
    context.fillRect(0, 0, canvas.width, canvas.height);

    const data = canvas.toDataURL('image/png');
    photo.setAttribute('src', data);
}

let width = 320;
let height = 0;

video.addEventListener('canplay', function(ev){
    if (!height) {
        height = video.videoHeight / (video.videoWidth/width);
    }

    video.setAttribute('width', width);
    video.setAttribute('height', height);
    canvas.setAttribute('width', width);
    canvas.setAttribute('height', height);
}, false);

startbutton.addEventListener('click', function(ev){
    takepicture();
    ev.preventDefault();
}, false);

startVideo();
