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


const SEND_DATA_TIMER = 10000;

const INFO_TIMER = 1000;



class App extends React.PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            mode: 'rating',
            stats: {},
            statsLoading: false,
            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',
                }
            });


            //let responseJson = await response.text();
            //return responseJson.movies;
        } 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);
        }
    }


    renderRating() {
        const buttons = [];
        for (let i = 5; i; i--) {
            let text = "";
            for (let j = 0; j < i; j++) {
                text += "*";
            }
            buttons.push(<TouchableOpacity key={ i } onPress={ this.onPress(i) }>
                <Text>{ text }</Text>
            </TouchableOpacity>
            );
        }

        return (
            <View style={styles.container}>
                <Text>Radegast Zóna</Text>
                { buttons }
            </View>
        );
    }


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

            try {
                this.setState({ mode: "info" });
                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" });
            }  
        }
    }


    renderResults() {
        return <View></View>
    }


    renderInfo() {
        return <View><Text>Děkujeme za hodnocení</Text></View>
    }


    render() {
        let { mode } = this.state;

        let content = null;

        switch (mode) {
            case 'results':
                content = this.renderResults();
                break;
            case 'info':
                content = this.renderInfo();
                break;
            default:
                content = this.renderRating();

        }

        return (
            <View style={styles.container}>
                <StatusBar hidden />
                { content }
            </View>
        );
    }


}


export default App;


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
});
