import React, { Component } from "react";
import { StyleSheet, Animated, Dimensions } from "react-native";
import { connect } from "react-redux";
import { getMainBrandingColourFromState } from "../colours";

const DEFAULT_HEIGHT = 4;
const DEFAULT_WIDTH = Dimensions.get("window").width;

class LoadingIndicator extends Component {
	constructor(props) {
		super(props);
		this.state = {
			animatedLeft: new Animated.Value(-DEFAULT_WIDTH),
			animatedOpacity: new Animated.Value(0),
		};
		this.height = 0;
	}

	componentDidMount() {
		this.animate();
	}

	getSnapshotBeforeUpdate(prevProps) {
		return null;
	}

	componentDidUpdate(prevProps) {
		if (prevProps.visible !== this.props.visible) {
			Animated.timing(this.state.animatedOpacity, {
				toValue: this.props.visible ? 0.8 : 0,
				duration: 300,
				useNativeDriver: false,
			}).start();
		}
	}

	animate = () => {
		Animated.sequence([
			Animated.timing(this.state.animatedLeft, {
				toValue: DEFAULT_WIDTH,
				duration: 1500,
				useNativeDriver: false,
			}),
			Animated.delay(500),
			Animated.timing(this.state.animatedLeft, {
				toValue: -DEFAULT_WIDTH,
				duration: 1500,
				useNativeDriver: false,
			}),
			Animated.delay(500),
		]).start(() => {
			this.animate();
		});
	};

	render() {
		return (
			<Animated.View
				style={[
					styles.container,
					this.props.style,
					{ height: DEFAULT_HEIGHT, opacity: this.state.animatedOpacity },
				]}
				onLayout={this.onLayout}
			>
				<Animated.View
					style={[
						styles.line,
						{
							backgroundColor: this.props.colourBrandingMain,
							left: this.state.animatedLeft,
							height: DEFAULT_HEIGHT,
						},
					]}
				/>
			</Animated.View>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		alignItems: "center",
		justifyContent: "center",
		overflow: "hidden",
		backgroundColor: "#fff",
		width: "100%",
		height: 38,
	},
	innerContainer: {
		flexDirection: "row",
	},
	line: {
		width: DEFAULT_WIDTH,
	},
});

const mapStateToProps = (state) => {
	return {
		colourBrandingMain: getMainBrandingColourFromState(state),
	};
};

export default connect(mapStateToProps, {})(LoadingIndicator);
// export { loadingIndicator as Default };
