import React, { useState } from 'react';
import {getDog} from '../services/PhpApi';
import useSWR from 'swr';
import { FileInput } from '@mantine/core';

function PreviewUpload({chgFile}:{chgFile: any}) 
{
  const [file, setFile] = useState('');
  const [dimensionWidth, setDimensionWidth] = useState(0);
  const [dimensionHeight, setDimensionHeight] = useState(0);

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

  const { data, error, isLoading } = useSWR(['PreviewUpload', 'SESS'], getDog );
  if (error) return (<div>failed to load</div>);
  if (isLoading) return (<div>loading...</div>);

  console.log('PreviewUpload getDog');
  console.log(data);
  let file_loc: string | undefined = "./uploads"+ data.data.picture;

  const handleChangeFile = async (pl: File) =>
  {
    console.log(pl);

    const fileLoaded = URL.createObjectURL(pl);

    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(pl);
  }

  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 ( <></> );
  return (
    <div className = 'frameCenter'>
      <FileInput 
//        label = 'Datei :'
        name="file" 
        placeholder="Bild auswählen" 
        id="file" 
        required 
        onChange={handleChangeFile}
        accept="image/jpg,.gif,.png,.svg,.webp audio/wav,.mp3"
      />
      <div className='prevUplImg'>
      <img
        src={file ? file : file_loc}
        style={{
          display: 'flex',
          border: '2px solid tomato',
          maxWidth: '300px',
          maxHeight: '300px',
        }}
      />
      </div>
      {file && <p>Dimensions: {`${dimensionWidth} x ${dimensionHeight}`}</p>}
    </div>
  );
}
export default PreviewUpload;

