import * as React from "react";
import { Image, ImageProps, ImageStyle } from "react-native";
import * as Url from "url-parse";
import { useSiteSettings } from "../../providers/site";

export interface SiteImageProps extends Omit<ImageProps, "source" | "style"> {
  src: string;
  fit?: boolean;
  setOriginalSize?: boolean;
  style?: ImageStyle;
}

export const SiteImage = React.memo(
  ({ src, setOriginalSize, fit, style, ...props }: SiteImageProps) => {
    const { settings } = useSiteSettings();
    const [size, setSize] = React.useState({ width: 0, height: 0 });

    if (!src) {
      return null;
    }

    const isAbsoluteUrl = (url: string) => url.indexOf("http") === 0;

    let uri = src;

    if (!isAbsoluteUrl(src)) {
      let newUrl = new Url(src);
      if (!isAbsoluteUrl(settings.domain.url)) {
        newUrl.set("protocol", "https:");
      }
      newUrl.set("host", settings.domain.url);
      newUrl.set("pathname", src);
      uri = newUrl.href;
    }

    React.useEffect(() => {
      if (setOriginalSize) {
        Image.getSize(
          uri,
          (width, height) => {
            setSize({ width, height });
          },
          (err) => {
            console.log("failed to get image", err);
          }
        );
      }
    }, []);

    return (
      <Image
        source={{ uri }}
        resizeMode="contain"
        {...props}
        style={
          {
            flex: 1,
            alignSelf: "stretch",
            ...(setOriginalSize
              ? { width: size.width, height: size.height }
              : {}),
            ...(fit && setOriginalSize
              ? {
                  maxWidth: "100%",
                  width: null,
                  height: null,
                  aspectRatio: size.width / size.height || 1,
                }
              : {}),
            ...(style as ImageStyle),
          } as any
        }
      />
    );
  }
);
