import React from 'react'
import { useRef, useEffect, useState } from 'react'

const ReceipeCanvas = props => {
  
  const canvasRef = useRef(null)
  const contextRef = useRef(null);

  const { image, myRef, setNewRect, ...rest } = props
  
  const [isDrawing, setIsDrawing] = useState(false);

  //const [data, setData] = useState(drawData)

  const canvasOffSetX = useRef(null);
  const canvasOffSetY = useRef(null);
  const startX = useRef(null);
  const startY = useRef(null);
  const rectWidth = useRef(null);
  const rectHeight = useRef(null);
  const imgWidth = useRef(null);
  const imgHeight = useRef(null);

  var ratio;

  const draw = (drawData) => {
        console.log('draw')
        //contextRef.current.beginPath();
        contextRef.current.strokeStyle="red";
        //contextRef.current.rect(drawData.location_x*ratio,drawData.location_y*ratio,drawData.location_w*ratio,drawData.location_h*ratio);
        //contextRef.current.stroke();

        const hRatio = contextRef.current.canvas.width / image.width;

        //Clears the entire canvas
        contextRef.current.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);

        //Redraw the background image
        contextRef.current.drawImage(image, 0,0, 
          image.width, 
          image.height, 
          0,0,
          image.width*hRatio, 
          image.height*hRatio);

        contextRef.current.strokeRect(drawData.location_x*hRatio,drawData.location_y*hRatio,drawData.location_w*hRatio,drawData.location_h*hRatio);
  }

  const drawImage = async (image) => {
    console.log('Draw image fkt')
    /*
    var img = new Image();
    img.onload = function(){
      imgWidth.current = img.naturalWidth
      imgHeight.current = img.naturalHeight;
      //console.log("width,height:", img.width, img.height);
      //console.log("offsetW,offsetH:", img.offsetWidth, img.offsetHeight);
    }
    img.src = image.src;
    */
    await image.decode()
    contextRef.current.clearRect(0, 0, contextRef.current.canvas.width, contextRef.current.canvas.height);

    ratio = contextRef.current.canvas.width / image.width;
    contextRef.current.canvas.height = image.height*ratio;
    contextRef.current.drawImage(image, 0,0, 
                            image.width, 
                            image.height, 
                            0,0,
                            image.width*ratio, 
                            image.height*ratio);

  
    console.log(image.width, ratio, contextRef.current.canvas.height)
  }

  myRef.current.draw = draw
  myRef.current.drawImage = drawImage
  

  useEffect(() => {
    const canvas = canvasRef.current
    const context = canvas.getContext('2d')
    context.canvas.width = 300
   
    context.clearRect(0, 0, context.canvas.width, context.canvas.height);
    ratio = context.canvas.width / image.width    ;
    context.canvas.height = image.height*ratio;
    
    context.drawImage(image, 0,0, 
                  image.width, 
                  image.height, 
                  0,0,
                  image.width*ratio, 
                  image.height*ratio);
    
    //draw(context,hRatio);

    contextRef.current = context;

      console.log('useeffect',image)
  },[image])
  
  const startDrawingRectangle = ({nativeEvent}) => {
    nativeEvent.preventDefault();
    nativeEvent.stopPropagation();

    const canvasOffSet = canvasRef.current.getBoundingClientRect();
    canvasOffSetX.current = canvasOffSet.left;
    canvasOffSetY.current = canvasOffSet.top;

    startX.current = nativeEvent.clientX - canvasOffSetX.current;
    startY.current = nativeEvent.clientY - canvasOffSetY.current;
    console.log('#nativ',nativeEvent.clientX,nativeEvent.clientY)
    setIsDrawing(true);
    console.log("Start drawing")
  };

  const drawRectangle = ({nativeEvent}) => {
    if (!isDrawing) {
        return;
    }

    nativeEvent.preventDefault();
    nativeEvent.stopPropagation();

    const newMouseX = nativeEvent.clientX - canvasOffSetX.current;
    const newMouseY = nativeEvent.clientY - canvasOffSetY.current;

    rectWidth.current = newMouseX - startX.current;
    rectHeight.current = newMouseY - startY.current;

    contextRef.current.strokeStyle="red";

    //Clears the entire canvas
    contextRef.current.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);

    //Redraw the background image
    const hRatio = contextRef.current.canvas.width / image.width;
    contextRef.current.drawImage(image, 0,0, 
      image.width, 
      image.height, 
      0,0,
      image.width*hRatio, 
      image.height*hRatio);

    contextRef.current.strokeRect(startX.current, startY.current, rectWidth.current, rectHeight.current);


  };

  const stopDrawingRectangle = ({nativeEvent}) => {
    nativeEvent.preventDefault();
    nativeEvent.stopPropagation();

    const hRatio = contextRef.current.canvas.width / image.width;
    console.log({location_x: startX.current/hRatio, location_y: startY.current/hRatio, location_w: rectWidth.current/hRatio,location_h: rectHeight.current/hRatio})
    if (startX.current/hRatio < 0){
      startX.current = 0;
    }
    if ((rectWidth.current < 0) && (rectHeight.current > 0)) {
      setNewRect({location_x: (startX.current+rectWidth.current)/hRatio, location_y: startY.current/hRatio, location_w: -rectWidth.current/hRatio,location_h: rectHeight.current/hRatio});
    }
    else if  ((rectWidth.current > 0) && (rectHeight.current < 0)) {
      setNewRect({location_x: startX.current/hRatio, location_y: (startY.current+rectHeight.current)/hRatio, location_w: rectWidth.current/hRatio,location_h: -rectHeight.current/hRatio});
    }
    else if  ((rectHeight.current < 0) && (rectWidth.current < 0)) {
      console.log('<<')
      setNewRect({location_x: (startX.current+rectWidth.current)/hRatio, location_y: (startY.current+rectHeight.current)/hRatio, location_w: -rectWidth.current/hRatio,location_h: -rectHeight.current/hRatio});
    }
    else {
      setNewRect({location_x: startX.current/hRatio, location_y: startY.current/hRatio, location_w: rectWidth.current/hRatio,location_h: rectHeight.current/hRatio});
    }

    setIsDrawing(false);

  };

  return <canvas 
            ref={canvasRef} 
            onMouseDown={startDrawingRectangle}
            onMouseMove={drawRectangle}
            onMouseUp={stopDrawingRectangle}
            //onMouseLeave={stopDrawingRectangle}
            {...rest}>
         </canvas>
}

ReceipeCanvas.defaultProps = {
  myRef: {current: {}}
}

export default ReceipeCanvas
