import React, { Component } from 'react';
import { ToastAndroid, AsyncStorage } from 'react-native';
import {
    Container,
    Content,
    Button,
    Icon,
    View,
    Text
} from 'native-base';
import {
    Col,
    Row,
    Grid
} from 'react-native-easy-grid'
import AppHeader from './../components/Header';
import ReminderBoxList from './../components/ReminderBoxList';
import { formatDate } from './../Utils';
import realm from './../Database';

class HomeScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            firstLaunch: null,
            active: false,
            today: formatDate(new Date(Date.now())),
            initDB: false,
            morningReminder: [],
            afternoonReminder: [],
            eveningReminder: [],
            nightReminder: [],
        };
    }

    componentWillMount() {
        this._isFirstLaunched()
        this._initDB()
        this._queryReminder()
    }

    render() {

        var { timePeriodLeftStyle, timePeriodRightStyle, dateTitle } = styles;

        return (
            <Container style={{ backgroundColor: 'white' }}>
                <AppHeader
                    headerText={'Pill Minder'}
                    headerLeft={
                        <Button onPress={this.onMenuPressed.bind(this)}>
                            <Icon name='menu' />
                        </Button>
                    }
                    headerRight={
                        <Button onPress={this.onAddMedicinePressed.bind(this)}>
                            <Icon name='add' />
                        </Button>
                    }
                />
                <Content style={{ flex: 1 }}>
                    <Text style={dateTitle}>{this.state.today}</Text>
                    <Grid>
                        <Col>
                            <Row>
                                <View style={timePeriodLeftStyle} >
                                    <ReminderBoxList
                                        periodText={"Morning"}
                                        items={this.state.morningReminder}
                                    />
                                </View>
                            </Row>
                            <Row>
                                <View style={timePeriodLeftStyle} >
                                    <ReminderBoxList
                                        periodText={"Afternoon"}
                                        items={this.state.afternoonReminder}
                                    />
                                </View>
                            </Row>
                        </Col>
                        <Col>
                            <Row>
                                <View style={timePeriodRightStyle} >
                                    <ReminderBoxList
                                        periodText={"Evening"}
                                        items={this.state.eveningReminder}
                                    />
                                </View>
                            </Row>
                            <Row>
                                <View style={timePeriodRightStyle} >
                                    <ReminderBoxList
                                        periodText={"Night"}
                                        items={this.state.nightReminder}
                                    />
                                </View>
                            </Row>
                        </Col>
                    </Grid>
                </Content>
            </Container >
        )

    }

    onHomePressed() {
        this.props.navigation.navigate('Home');
    }

    onCameraPressed() {
        this.props.navigation.navigate('Camera');
    }

    onAddMedicinePressed() {
        this.props.navigation.navigate('AddMedication')
    }

    onMenuPressed() {
        this.props.navigation.navigate('DrawerToggle');
    }

    _timePeriodPress(data, period) {
        // ToastAndroid.show(JSON.stringify(data), ToastAndroid.SHORT)
        this.props.navigation.navigate('Detail', { items: data, period: period })
    }

    _queryReminder() {
        let myReminder = realm.objects('Reminder')
        let morningReminder = myReminder.filtered('period == 1')
        let afternoonReminder = myReminder.filtered('period == 2')
        let eveningReminder = myReminder.filtered('period == 3')
        let nightReminder = myReminder.filtered('period == 4')

        var tmpMorning = []
        morningReminder.forEach(i => {
            tmpMorning.push(i)
        });

        var tmpAfternoon = []
        afternoonReminder.forEach(i => {
            tmpAfternoon.push(i)
        })

        var tmpEvening = []
        eveningReminder.forEach(i => {
            tmpEvening.push(i)
        })

        var tmpNight = []
        nightReminder.forEach(i => {
            tmpNight.push(i)
        })


        this.setState({ morningReminder: tmpMorning, afternoonReminder: tmpAfternoon, eveningReminder: tmpEvening, nightReminder: tmpNight })

        // ToastAndroid.show(JSON.stringify(myReminder), ToastAndroid.LONG)
        // ToastAndroid.show(JSON.stringify(this.state.morningReminder), ToastAndroid.LONG)
    }

    _isFirstLaunched() {
        AsyncStorage.getItem("alreadyLaunched").then(value => {
            if (value == null) {
                AsyncStorage.setItem('alreadyLaunched', 'true')
                    .catch(error => {
                        ToastAndroid.show(error.toString(), ToastAndroid.SHORT)
                    }) // No need to wait for `setItem` to finish, although you might want to handle errors
                this.setState({ firstLaunch: true });
                // ToastAndroid.show("Frist Launch:" + this.state.firstLaunch, ToastAndroid.LONG)
            } else {
                this.setState({ firstLaunch: false });
                // ToastAndroid.show("Frist Launch:" + this.state.firstLaunch, ToastAndroid.LONG)
            }
        }) // Add some error handling, also you can simply do this.setState({fistLaunch: value == null})
    }

    _initDB() {

        AsyncStorage.getItem("alreadyInitDB").then(value => {
            if (value == null) {
                ToastAndroid.show("Init DB", ToastAndroid.LONG)
                AsyncStorage.setItem('alreadyInitDB', 'true')
                realm.write(() => {
                    realm.create('TimePeriod', {
                        morning: '08:00',
                        afternoon: '12:00',
                        evening: '16:00',
                        night: '20:00'
                    })
                })
            }
        })
    }

}

const styles = {
    timePeriodLeftStyle: {
        flex: 1,
        marginLeft: 20,
        marginRight: 10,
        marginTop: 20,
        marginBottom: 20
    },
    timePeriodRightStyle: {
        flex: 1,
        marginLeft: 10,
        marginRight: 20,
        marginTop: 20,
        marginBottom: 20
    },
    dateTitle: {
        fontSize: 20,
        textAlign: 'center',
        marginTop: 20,
        marginLeft: 20,
        marginLeft: 20,
        marginBottom: 10,
    }
}

export default HomeScreen;