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

class HomeScreen extends Component {
  constructor() {
    super();
    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 { containerStyle, 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>
                <TouchableOpacity style={timePeriodLeftStyle} onPress={() => this._timePeriodPress(this.state.morningReminder)}>
                  <ReminderList
                    periodText={"Morning"}
                    items={this.state.morningReminder}
                  />
                </TouchableOpacity>
              </Row>
              <Row>
                <TouchableOpacity style={timePeriodLeftStyle} onPress={() => this._timePeriodPress(this.state.afternoonReminder)}>
                  <ReminderList
                    periodText={"Afternoon"}
                    items={this.state.afternoonReminder}
                  />
                </TouchableOpacity>
              </Row>
            </Col>
            <Col>
              <Row>
                <TouchableOpacity style={timePeriodRightStyle} onPress={() => this._timePeriodPress(this.state.eveningReminder)}>
                  <ReminderList
                    periodText={"Evening"}
                    items={this.state.eveningReminder}
                  />
                </TouchableOpacity>
              </Row>
              <Row>
                <TouchableOpacity style={timePeriodRightStyle} onPress={() => this._timePeriodPress(this.state.nightReminder)}>
                  <ReminderList
                    periodText={"Night"}
                    items={this.state.nightReminder}
                  />
                </TouchableOpacity>
              </Row>
            </Col>
          </Grid>
        </Content>
      </Container >
    )

  }

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

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

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

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

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

  _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;