import React, { useState } from 'react';
import { Connect } from 'react-native-younify-connect-sdk';

import
{
  Image,
  type ImageStyle,
  type StyleProp
} from 'react-native';

interface ImageProps
{
  connect: Connect;
  url?: string;
  style:  StyleProp<ImageStyle>;
  name: string;
}

const YCImage = (props: ImageProps) =>
{
  const base64Flag = 'data:image/jpeg;base64,';
  const [imageUrlState, setImageUrlState] = useState<string>(base64Flag);

  const loadImage = () =>
  {
    setImageUrlState(base64Flag);
    if (props.url)
    {
      props.connect.fetchImage(props.url, null).then((data) =>
      {
        setImageUrlState(base64Flag + data);
      })
      .catch(() =>
      {
        setImageUrlState(base64Flag);
      });
    }
  };

  React.useEffect(() =>
  {
    loadImage();
  }, [props?.url]);

  return <Image src={imageUrlState} style={props.style}/>;
}

export default YCImage;
