import React, { useMemo } from "react";
import PropTypes from "prop-types";
import UnknownResourceType from "../../../../images/UnknownResourceType.jpg";
import style from "../styles";
import { makeStyles } from "@material-ui/core/styles";
import { useResourceSecurity } from "../../../../hooks";

const useStyles = makeStyles(style);

const RESOURCE_TYPES = {
  UNKNOWN: "UNKNOWN",
  IMAGE: "IMAGE"
};

const getResourceType = (mimeType) => {
  if (mimeType.startsWith("image/")) return RESOURCE_TYPES.IMAGE;
  return RESOURCE_TYPES.UNKNOWN;
};

const ResourcePreviewComponent = ({ resource }) => {
  const classes = useStyles();
  const { secureUrl } = useResourceSecurity();

  const resourceType = useMemo(() => getResourceType(resource.mimeType), [
    resource.mimeType
  ]);

  const resourceUrl = useMemo(
    () => (resource.secured ? secureUrl(resource.urls[2]) : resource.urls[2]),
    [resource.secured, resource.urls, secureUrl]
  );

  const isImage = useMemo(() => resourceType === RESOURCE_TYPES.IMAGE, [
    resourceType
  ]);
  const isUnknown = useMemo(() => resourceType === RESOURCE_TYPES.UNKNOWN, [
    resourceType
  ]);

  return (
    <>
      {isImage && (
        <img src={resourceUrl} alt="..." className={classes.resourceImage} />
      )}

      {isUnknown && (
        <img
          src={UnknownResourceType}
          alt="..."
          className={classes.resourceImage}
        />
      )}
    </>
  );
};

ResourcePreviewComponent.propTypes = {
  resource: PropTypes.object.isRequired
};

export default ResourcePreviewComponent;
