import React, { useState, createContext, useEffect } from 'react';
import Styled from 'styled-components/native';
import { Image, Animated } from 'react-native';
import { SplashScreen } from 'expo';
import { Util } from '~/Utils/utils';
import { Asset } from 'expo-asset';

const initialValue = { state:{ visible:true }, hide:()=>{} };
export const SplashContext = createContext(initialValue);

export const SplashProvider = ({children}) => {
    const [visible, setVisible] = useState(true);

    initialValue.hide = () => {
        //SplashScreen.hide();
        setVisible(false);
    };

    return (
        <SplashContext.Provider value={initialValue}>
            {children}
            <Splash visible={visible} />
        </SplashContext.Provider>
    )
}

const SplashContainer = Styled(Animated.View)`
  position: absolute;
  left: 0; top: 0; right: 0; bottom: 0;
  justify-content: center;
  align-items: center;
`;
const Splash = ({visible=true}) => {
    const [hide, setHide] = useState(!visible);
    const [loaded, setLoaded] = useState(false);
    const [ready, setReady] = useState(false);
    const [opacityValue] = useState(new Animated.Value(1));
    const [position] = useState(new Animated.ValueXY({x:0,y:0}));

    const hideAnimation = () => {
        Animated.timing(opacityValue, {
            toValue: 0,
            duration: 500,
            useNativeDriver: true,
        }).start();

        Animated.timing(position, {
            toValue: {x:-Util.getScreenWidth(), y:0},
            duration: 300,
            useNativeDriver: true,
        }).start(() => {
            setHide(true);
        });
    }

    useEffect(() => {
        if(!visible && loaded && ready) {
            SplashScreen.hide();
            hideAnimation();
        }
        if(!loaded) {
            cacheResourcesAsync()
                .then(() => setLoaded(true))
                .catch(error => console.error(`splash image load error - ${error}`));
        }
    }, [visible, ready, loaded]);

    const cacheResourcesAsync = async () => {
        const images = [require('./../../../assets/splash.png')];
        const cacheImages = images.map(image => Asset.fromModule(image).downloadAsync());
        return Promise.all(cacheImages);
    }

    return (
        !hide && loaded && (
            <SplashContainer style={{opacity:opacityValue, transform:[{ translateX:position.x }, { translateY:position.y }]}}>
                <Image
                    style={{width:'100%', height:'100%'}}
                    source={require('./../../../assets/splash.png')}
                    resizeMode="cover"
                    onLoadEnd={() => { setReady(true) }}
                    fadeDuration={0}
                />
            </SplashContainer>
        )
    )
}
