import React from 'react';
import io from 'socket.io-client';
import { server_ip } from '../../constants';

import './style.css'

const cam_img_web = function cam_img_web(data){
    // console.log("cam_img_web", data);
    const imgData = 'data:image/jpeg;base64,' + data.image;
    const width = this.canvas.clientWidth;
    const height = this.canvas.clientHeight;
    const image = new Image();
    const ctx = this.canvas.getContext("2d");
    image.onload = () => {
        ctx.drawImage(image, 0, 0,  width,  height);
        if(this.props.computeFeaturePoints){
            const imageData = ctx.getImageData(0, 0, width, height);
            console.log('computeFeaturePoints');
            const widthHalf = width / 2, heightHalf = height / 2;
            for (let i = 0; i < this.props.pointCloud.length; i++) {
                const point = this.props.pointCloud[i];
                point.project(this.props.camera);
                point.x = ( point.x * widthHalf ) + widthHalf;
                point.y = - ( point.y * heightHalf ) + heightHalf;
                let idx = point.x * width + point.y;
                idx = Math.round(idx);
                idx *= 4;
                imageData.data[idx] = 0;
                imageData.data[idx + 1] = 255;
                imageData.data[idx + 2] = 0;
            }
            imageData.data[0] = 0;
            imageData.data[1] = 255;
            imageData.data[2] = 0;
            console.log('computeFeaturePoints finished');
            ctx.putImageData(imageData, 0, 0);
        }
    };
    image.src = imgData;
};


class CameraImage extends React.Component{
    constructor(props) {
        super(props);
        this.cam_img_web = cam_img_web.bind(this);
    }

    componentDidMount(){
        const socket = io(server_ip);
        socket.on('cam_img_web', this.cam_img_web);
    }
    render(){
        return(
            <canvas width="320" height="240" className={"camera_image"}
                ref={(mount) => { this.canvas = mount }}
            >
            </canvas>
        )
    }
}
export default CameraImage;
