import React, { Component } from 'react';
import { BackHandler, ToastAndroid, Alert } from 'react-native';
import {
  Dimensions,
  StyleSheet,
  Text,
  View
} from 'react-native';
import { Container, Header, Content, Icon, Button } from 'native-base';
import { MaterialDialog } from 'react-native-material-dialog'
import Camera from 'react-native-camera';
import { scheduleLocalNotification, appointmentNotification } from './../Utils';
import moment from 'moment';
import realm from './../Database/';

class AppCamera extends Component {

  constructor(props) {
    super(props)
    this.state = {
      morningTime: "",
      afternoonTime: "",
      eveningTime: "",
      nightTime: "",
      addItemVisible: true,
      visible: true,
    }
  }

  componentWillMount() {
    let timePeriod = realm.objects('TimePeriod')
    var morningTime = timePeriod[0].morning
    var afternoonTime = timePeriod[0].afternoon
    var eveningTime = timePeriod[0].evening
    var nightTime = timePeriod[0].night

    this.setState({ morningTime, afternoonTime, eveningTime, nightTime })
  }

  render() {
    return (
      <Container style={styles.container}>
        <Camera
          ref={(cam) => {
            this.camera = cam;
          }}
          style={styles.preview}
          aspect={Camera.constants.Aspect.fill}
          captureTarget={Camera.constants.CaptureTarget.temp}
          playSoundOnCapture={false}
          onBarCodeRead={(data, type) => this._onBarCodeRead(data, type)}
          defaultTouchToFocus>

          <Button onPress={this.takePicture.bind(this)} style={styles.capture}>
            <Text>[CAPTURE]</Text>
          </Button>
        </Camera>
      </Container >
    );
  }

  takePicture() {
    const options = {};
    //options.location = ...
    this.camera.capture({ metadata: options })
      .then((data) => {
        // ToastAndroid.show(data.path, ToastAndroid.SHORT);
        this.props.navigation.navigate("PreviewPhoto", { photo: data })
      })
      .catch(err => console.error(err));
  }

  _onBarCodeRead(data, type) {
    if (data.type == 'QR_CODE') {
      var tmpData = JSON.parse(decodeURI(data.data))
      switch (tmpData.type) {
        case "medicine":
          if (this.state.addItemVisible) {
            this._addMedicine(tmpData)
            this.setState({ addItemVisible: false })
          }
          break;
        case "appointment":
          if (this.state.addItemVisible) {
            this._addAppointment(tmpData)
            this.setState({ addItemVisible: false })
          }
          break;
      }
    }

  }

  _addMedicine(data) {

    var time = null

    switch (data.period) {
      case 1:
        time = this.state.morningTime.split(":")
        break;
      case 2:
        time = this.state.afternoonTime.split(":")
        break;
      case 3:
        time = this.state.eveningTime.split(":")
        break;
      case 4:
        time = this.state.nightTime.split(":")
        break;
    }

    var timePeriod = data.period == 1 ? 'เช้า' : data.period == 2 ? 'กลางวัน' : data.period == 3 ? 'เย็น' : 'ค่ำ';
    var beforeMeal = data.beforeMeal ? "\tก่อนอาหาร" : "\tหลังอาหาร";


    Alert.alert(
      'Confirm',
      'ชื่อยา: ' + data.medName + '\nก่อน/หลัง อาหาร: ' + beforeMeal + '\nช่วงเวลา: ' + timePeriod + '\nจำนวน: ' + data.dose,
      [
        { text: 'CANCLE', onPress: () => this.setState({ addItemVisible: true }) },
        {
          text: 'OK', onPress: () => {

            var id = Math.random() * 10000
            var reminderDate = moment().hour(time[0]).minute(time[1]).second(0).toDate()


            var msg = "แจ้งเตือนกินยา\n" + "เวลา: " + time[0] + ":" + time[1] + "\nยา: " + data.medName + beforeMeal;
            scheduleLocalNotification(msg, reminderDate, id)

            realm.write(() => {
              realm.create('Reminder', {
                id: id,
                medName: data.medName,
                reminderTime: reminderDate,
                meal: beforeMeal.trim(),
                period: data.period,
                dose: data.dose.toString(),
                timeStamp: moment().toDate()
              })
            })

            this.props.navigation.goBack(null)
          }
        },
      ],
      { cancelable: false }
    )
  }

  _addAppointment(data) {

    const time = data.date.split(':')

    Alert.alert(
      'Confirm',
      "Doctor: " + data.doctorName + "\nDate: " + moment(data.date).format("DD MMM YYYY") + "\nTime: " + moment(data.date).format("HH:mm") + "\nPlace: " + data.place,
      [
        { text: 'CANCLE', onPress: () => this.setState({ addItemVisible: true }) },
        {
          text: 'OK', onPress: () => {
            var id = Math.random() * 10000
            var appointmentDate = moment(data.date).hour(time[0]).minute(time[1]).second(0).toDate()
            var msg = "แจ้งเตือนการนัดพบแพทย์\n" + "แพทย์: " + data.doctorName + "เวลา: " + moment(data.date).format("HH:mm")
            appointmentNotification(msg, appointmentDate, id)

            realm.write(() => {
              realm.create('Appointments', {
                id: id,
                doctorName: data.doctorName,
                date: appointmentDate,
                place: data.place,
                timeStamp: moment().toDate()
              })
            })

            this.props.navigation.goBack(null)
          }
        },
      ],
      { cancelable: false }
    )

  }


}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
  },
  capture: {
    flex: 0,
    backgroundColor: '#fff',
    borderRadius: 5,
    padding: 10,
    margin: 40,
    alignItems: 'center',
    alignSelf: 'center'
  }
});

export default AppCamera;