import * as React from 'react';
import * as Animatable from 'react-native-animatable';

import { Props } from './fade-in-out-animation.props';

/**
 * Fade in-out animation component
 *
 * @property animation Animation type (fadeIn|fadeOut)
 * @property children Component to animate
 * @property duration Duration of the animation.
 * @property delay Delay of the animation.
 * @property visibleTime Time the animation is visible.
 * @property onAnimationEnd Callback executed when the animation ends
 */
export const FadeInOutAnimation: React.FC<Props> = (props) => {
  // grab the props
  const { children, duration, delay, visibleTime, style, onAnimationEnd, ...rest } = props;

  const totalTime = duration * 2 + visibleTime + delay;
  const start = delay / totalTime;
  const endZoomIn = duration / totalTime;
  const startZoomOut = visibleTime / totalTime;
  const zoomInOut = {
    [start]: {
      opacity: 0,
      scale: 1,
    },
    [start + endZoomIn]: {
      opacity: 1,
      scale: 1,
    },
    [endZoomIn + startZoomOut]: {
      opacity: 1,
      scale: 1,
    },
    1: {
      opacity: 0,
      scale: 1,
    },
  };

  return (
    <Animatable.View
      animation={zoomInOut}
      duration={totalTime}
      style={style}
      onAnimationEnd={onAnimationEnd}
      {...rest}
    >
      {children}
    </Animatable.View>
  );
};

FadeInOutAnimation.defaultProps = {
  delay: 0,
  onAnimationEnd: () => null,
};
