import React, { useContext, useState } from 'react';
import { Axios, ResponseT, UserCtx, UserCtxT } from '../context/UserContext';

function PreviewUpload({chgFile}:{chgFile: any}) {
  const [file, setFile] = useState<string | undefined >(undefined);
  const [dimensionWidth, setDimensionWidth] = useState(0);
  const [dimensionHeight, setDimensionHeight] = useState(0);

  const { user } = useContext<UserCtxT | null>(UserCtx) as UserCtxT;
  const [dog, setDog] = useState<ResponseT | any>({}); // local dog not the dog in UserContext

  if(user && (dog === undefined || dog.success === undefined))
  {
	  Axios.post<ResponseT>('getDog.php', 
	  {
		  qr_id: user.qr_id
	  })
	  .then((resDog) =>
	  {
		  setDog(resDog.data);
      setFile("./uploads"+resDog.data.data.picture);
	  })
	  .catch((err) => console.error(err));
  }


  const handleChange = async (
    event: React.ChangeEvent<HTMLInputElement>
  ): Promise<any> => {
    // const { target } = event;
    // const img = new Image();
    const ImageName = event.target.value.split('\\')[2];
    const Image = event.target.value;
    console.log('Imageon Kevel: ', Image); // Image on Kevel
    console.log('ImageName on Kevel: ', ImageName); // ImageName on Kevel
    console.log('ImageLink on Kevel: ', event.target.value); // ImageLink on Kevel
    console.log('event current Target files: ', event.target.files![0]);

    const fileLoaded = URL.createObjectURL(event.target.files![0]);
    const files = event.target.files;

    console.log('files: ', files);
    const dimensions = await someFunction(fileLoaded);
    setDimensionWidth(dimensions.width);
    setDimensionHeight(dimensions.height);
    console.log('dimensions: ', dimensions);
    console.log('dimensions width: ', dimensions.width);
    console.log('dimensions height: ', dimensions.height);
    setFile(fileLoaded);

    chgFile(event);
  };
  const getHeightAndWidthFromDataUrl = (dataURL: string) =>
    new Promise<{height: number, width: number}>((resolve) => {
      const img = new Image();
      img.onload = () => {
        resolve({
          height: img.height,
          width: img.width,
        });
      };
      img.src = dataURL;
    });
  // Get dimensions
  const someFunction = async (file: any) => {
    console.log('file: ', file);
    const dimensions = await getHeightAndWidthFromDataUrl(file);
    return dimensions;
  };

  return (
    <div>
      <input
        type="file"
        onChange={handleChange}
        accept="image/jpg,.gif,.png,.svg,.webp audio/wav,.mp3"
      />
      <img
        src={file}
        style={{
          display: 'flex',
          border: '2px solid tomato',
          maxWidth: '300px',
          maxHeight: '300px',
        }}
      />
      {file && <p>Dimensions: {`${dimensionWidth} x ${dimensionHeight}`}</p>}
    </div>
  );
}
export default PreviewUpload;
