import React from 'react';
import { Text, View, TouchableOpacity, AsyncStorage, StatusBar, Image } from 'react-native';

import EStyleSheet from 'react-native-extended-stylesheet';


const SEND_DATA_TIMER = 60000;

const INFO_TIMER = 1000;



class App extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            mode: 'rating',
            lastRating: null,
            buffer: []
        };

        this.sendData = this.sendData.bind(this);
        this.onPress = this.onPress.bind(this);
    }

    componentDidMount() {
        this.timer = setInterval(this.sendData, SEND_DATA_TIMER);
    }

    componentWillUnmount() {
        if (this.timer) {
            clearInterval(this.timer);
        }
    }


    async sendData() {
        let { buffer } = this.state;
        let body = [];

        //prepare body
        while (buffer.length) {
            body.push(buffer.shift());
        }

        if (!body.length) {
            // do nothing
            return;
        }

        let response;
        try {
            
            response = await fetch('https://radegast.janhrabal.com/api/ratings', {
                method: "POST",
                body: JSON.stringify(body),
                headers: {
                    'Content-Type': 'application/json',
                }
            });

        } catch (error) {
            //console.error(error);
            // return to buffer
            while (body.length) {
                buffer.push(body.shift());
            }

            response && console.warn("status " + response.status);
            console.warn("sendData - error", this.state.buffer);
        }
    }


    onPress(r) {
        return async () => {
            let { buffer } = this.state;
            let key = new Date().getTime();
            let rating = { rating: r, key };

            try {
                this.setState({ mode: "info", lastRating: r });
                await AsyncStorage.setItem(JSON.stringify(key), JSON.stringify(rating));

                //add to buffer
                buffer.push(rating);

                setTimeout(() => this.setState({ mode: "rating" }), INFO_TIMER);

            } catch (e) {
                console.error(e);
                this.setState({ mode: "rating" });
            }  
        }
    }


    render() {
        let { mode, lastRating } = this.state;
        let showInfo = mode == "info";

        const buttons = [];
        for (let i = 1; i <= 10; i++) {
            buttons.push(
                <TouchableOpacity key={ i } onPress={ this.onPress(i) }>
                    <View style={styles.rating}>
                        <View style={styles.ratingNumber}><Text>{ i }</Text></View>
                        { showInfo && lastRating && i <= lastRating ? <Image source={ require('./assets/siska.png') } style={ styles.ratingImage } /> : null }
                    </View>
                </TouchableOpacity>
            );
        }

        return (
            <View style={styles.container}>
                <StatusBar hidden />
                <Image source={ require('./assets/bg.jpg') } style={ styles.bg }/>
                <View style={styles.ratingsContainer}>
                    { buttons }
                </View>
            </View>
        );
    }


}


export default App;



EStyleSheet.build({});
const styles = EStyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#000000',
        width: '100%',
        height: '100%'
    },

    center: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },

    bg: {
        width: '100%', 
        height: '100%', 
        position: 'absolute',
        resizeMode: 'stretch'
    },

    ratingsContainer: {
        position: 'absolute',
        left: 0,
        top: '34%',
        width: '100%',
        flexDirection: 'row',
        alignItems: 'flex-start',
        justifyContent: 'space-around',
        color: '#FFFFFF',
        paddingLeft: '5%',
        paddingRight: '5%'
    },

    rating: {
        flexDirection: 'column',
        justifyContent: 'flex-start',
        alignItems: 'center',
        position: 'relative'
    },

    ratingNumber: {
        backgroundColor: '#FFFFFF',
        fontSize: '1.4rem',
        borderRadius: '1rem',
        width: '2rem',
        height: '2rem',
        textAlign: 'center',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
    },

    ratingImage: {
        resizeMode: 'contain',
        position: 'absolute',
        top: '3rem',
        height: '4.5rem'

    }

});