import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Animated, Easing } from 'react-native';
import NativeLinearGradient from 'react-native-linear-gradient';
import rgb2hex from 'rgb2hex';

class LinearGradient extends Component {
	render() {
		const { color0, color1, style } = this.props;
		return (
			<NativeLinearGradient
				colors={[ color0, color1 ].map((c) => rgb2hex(c).hex)}
				start={{ x: 0, y: 0 }}
				end={{ x: 1, y: 0 }}
				style={[ style ]}
			>
				{this.props.children}
			</NativeLinearGradient>
		);
	}
}
Animated.LinearGradient = Animated.createAnimatedComponent(LinearGradient);

export const presetColors = {
	instagram: [
		'rgb(106, 57, 171)',
		'rgb(151, 52, 160)',
		'rgb(197, 57, 92)',
		'rgb(231, 166, 73)',
		'rgb(181, 70, 92)'
	],
	firefox: [ 'rgb(236, 190, 55)', 'rgb(215, 110, 51)', 'rgb(181, 63, 49)', 'rgb(192, 71, 45)' ],
	sunrise: [
		'rgb(92, 160, 186)',
		'rgb(106, 166, 186)',
		'rgb(142, 191, 186)',
		'rgb(172, 211, 186)',
		'rgb(239, 235, 186)',
		'rgb(212, 222, 206)',
		'rgb(187, 216, 200)',
		'rgb(152, 197, 190)',
		'rgb(100, 173, 186)'
	]
};

class AnimatedGradient extends Component {
	static defaultProps = {
		customColors: presetColors.instagram,
		speed: 2000
	};

	state = { color0: new Animated.Value(0), color1: new Animated.Value(0) };

	componentDidMount = () => {
		this.startAnimation();
	};

	startAnimation = () => {
		const { color0, color1 } = this.state;
		const { colors, speed } = this.props;
		[ color0, color1 ].forEach((color) => color.setValue(0));

		Animated.parallel(
			[ color0, color1 ].map((animatedColor) => {
				return Animated.timing(animatedColor, {
					toValue: colors.length,
					duration: colors.length * speed,
					easing: Easing.linear
				});
			})
		).start(this.startAnimation);
	};

	render() {
		const { color0, color1 } = this.state;
		const { colors, children, style } = this.props;
		const preferColors = [];
		while (preferColors.length < 2) {
			preferColors.push(colors.slice(preferColors.length).concat(colors.slice(0, preferColors.length + 1)));
		}
		const interpolatedColors = [ color0, color1 ].map((animatedColor, index) => {
			return animatedColor.interpolate({
				inputRange: Array.from({ length: colors.length + 1 }, (v, k) => k),
				outputRange: preferColors[index]
			});
		});

		return (
			<Animated.LinearGradient style={[ style ]} color0={interpolatedColors[0]} color1={interpolatedColors[1]}>
				{children}
			</Animated.LinearGradient>
		);
	}
}
export default AnimatedGradient;
