import { Box } from "@mui/material";
import { pond } from "protobuf-ts/pond";
import { useFileControllerAPI } from "providers";
import React, { useEffect, useState } from "react";

interface Props {
  image: pond.FileReference;
  height?: number | string;
  width?: number | string;
}

export default function ImageViewer(props: Props) {
  const { image, height, width } = props;
  const fileController = useFileControllerAPI();
  // const [contentType, setContentType] = useState("")
  const [imageData, setImageData] = useState("");

  useEffect(() => {
    //check local storage for the image
    let imageURL = localStorage.getItem(image.uuid);
    if (imageURL !== null) {
      setImageData(imageURL);
    } else {
      //if its not there retrieve it
      fileController
        .retrieveFile(image.spacesPath)
        .then(resp => {
          let url = URL.createObjectURL(resp.data);
          setImageData(url);
          let reader = new FileReader();
          reader.addEventListener("load", () => {
            //store the file url in base64 in local storage so it doesn't need to be loaded everytime
            localStorage.setItem(image.uuid, reader.result as string);
          });
          reader.readAsDataURL(resp.data);
        })
        .catch(err => {
          //console.log("There were errors retrieving the file");
        });
    }
  }, [image, fileController]);

  //get the file from digital ocean by using our backend as a proxy

  return (
    <Box>
      <a href={imageData} download={image.fileName}>
        <img src={imageData} alt={image.fileName} style={{ maxHeight: height, maxWidth: width }} />
      </a>
    </Box>
  );
}
