import {Text, View, Dimensions} from 'react-native';
import LottieView from 'lottie-react-native';
import React from 'react';
import PropTypes from "prop-types";

const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;



class ViewReady extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            animation: this.getAnimation(this.props.animations)
        }
    }

    getAnimation(animations) {
        let randomNumber = Math.floor(Math.random() * animations.length) + 1;
        randomNumber -= 1;
        return animations[randomNumber];
    }

    showAnimation() {
        return (
            <View style={{flex: 1, marginTop: 20, marginBottom: 30, justifyContent: 'center', alignItems: 'center'}}>
                <LottieView
                    style={{width: SCREEN_WIDTH * 0.5, height: SCREEN_HEIGHT * 0.37}}
                    source={this.state.animation} resizeMode='cover' speed={1}
                    autoPlay loop/>

            </View>
        );
    }

    render(){
        if (this.props.ready) {
            return (
                <View {...this.props}>
                    {this.props.children}
                </View>
            )
        } else {
            return (
                <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                    <View style={{flex: this.props.hasExtraLoadingInfo ? 0.6  : 1, justifyContent: 'center'}}>
                        {this.showAnimation(this.props.animation)}
                        {this.props.hasExtraLoadingInfo ?
                            <View style={{flex: 0.3, alignItems: 'center', justifyItems: 'center'}}>
                                {

                                    <View style={{alignItems: 'center', justifyContent: 'center'}}>
                                        <Text style={{fontSize: 18, fontWeight: 'bold'}}>{this.props.message}</Text>
                                        <LottieView source={this.props.loadingBarAnimation}
                                                    style={{width: 300, marginTop: -60}} speed={0.5} autoPlay loop/>
                                    </View>
                                }
                            </View>
                            :
                            undefined}
                    </View>
                </View>
            );
        }
    }

};

ViewReady.propTypes = {
    animations: PropTypes.oneOf([PropTypes.array, PropTypes.object]).isRequired,
    ready: PropTypes.bool.isRequired,
    message: PropTypes.string,
    hasExtraLoadingInfo: PropTypes.bool,
    loadingBarAnimation: PropTypes.object
};


ViewReady.defaultProps = {
    loadingBarAnimation: require('./../animations/loadingBar'),
    hasExtraLoadingInfo: false,
    message: "Carregando dados...",
};

export default ViewReady;
