import React, { Component } from 'react';
import { BackHandler, ToastAndroid, Alert } from 'react-native';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity
} from 'react-native';
import { IMAGE_TO_TEXT } from './../ServiceUrl';
import { Container, Header, Content, Icon, Button } from 'native-base';
import { MaterialDialog } from 'react-native-material-dialog';
import { RNCamera } from 'react-native-camera';
import { scheduleLocalNotification, appointmentNotification, futch, generateID } from './../Utils';
import { connect } from 'react-redux'
import { reminderCreate, appointmentCreate } from './../actions'
import ReminderDialogForm from './../components/ReminderDialogForm';
import moment from 'moment';
import realm from './../Database/';

class AppCamera extends Component {

  constructor(props) {
    super(props)
    this.state = {
      morningTime: "",
      afternoonTime: "",
      eveningTime: "",
      nightTime: "",
      addItemVisible: false,
      visible: false,
      imageToText: "",
      uploadProgress: "0",
      addReminder: false,
      dataType: '',
      qrData: {},
      uuid: ''
    }
  }

  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}>
        <RNCamera
          ref={ref => {
            this.camera = ref;
          }}
          style={styles.preview}
          type={RNCamera.Constants.Type.back}
          fixOrientation={true}
          onBarCodeRead={(data, type) => this._onBarCodeRead(data, type)}
          permissionDialogTitle={'Permission to use camera'}
          permissionDialogMessage={'We need your permission to use your camera phone'}
        />
        <View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center', }}>
          <TouchableOpacity
            onPress={this.takePicture.bind(this)}
            style={styles.capture}
          >
            <Text style={{ fontSize: 14 }}> SNAP </Text>
          </TouchableOpacity>
        </View>
        <MaterialDialog
          title="Add Reminder"
          visible={this.state.visible}
          onOk={() => this.setState({ visible: false, imageToText: '', uploadProgress: '0' })}
          onCancel={() => this.setState({ visible: false, imageToText: '', uploadProgress: '0' })}>
          <ReminderDialogForm
            uploadProgress={this.state.uploadProgress}
            imageToText={this.state.imageToText}
          />
        </MaterialDialog>
        <MaterialDialog
          title="QRcode"
          visible={this.state.addItemVisible}
          onOk={() => this.addQr(this.state.uuid, this.state.dataType, this.state.qrData)}
          onCancel={() => this.setState({ addItemVisible: false, dataType: '', qrData: {} })}>
          <Text>{JSON.stringify(this.state.qrData)}</Text>
        </MaterialDialog>
      </Container >
    );
  }

  takePicture = async function () {
    this.setState({ visible: true })

    if (this.camera) {
      const options = { quality: 0.5, base64: true };
      const data = await this.camera.takePictureAsync(options)
      const image = new FormData()
      image.append('image', {
        uri: data.uri,
        type: 'imge/jpeg',
        name: 'image'
      })

      futch(IMAGE_TO_TEXT, {
        method: 'post',
        body: image
      }, (progressEvent) => {
        const progress = (progressEvent.loaded / progressEvent.total) * 100;
        this.setState({ uploadProgress: parseInt(progress).toString() })
      }).then(res => {
        this.setState({ imageToText: JSON.parse(res._response) })
      }).catch(err => {
        this.setState({ imageToText: JSON.stringify(err) })
      })

    }
  }

  _onBarCodeRead(data, type) {
    if (data.type == 'QR_CODE') {
      var tmpData = JSON.parse(decodeURI(data.data))
      let id = generateID()
      switch (tmpData.type) {
        case "reminder":
          if (!this.state.addItemVisible) {
            this.setState({ addItemVisible: true, dataType: tmpData.type, qrData: tmpData, uuid: id })
          }
          break;
        case "appointment":
          if (!this.state.addItemVisible) {
            this.setState({ addItemVisible: true, dataType: tmpData.type, qrData: tmpData, uuid: id })
          }
          break;
      }
    }
  }
  addQr(id, dataType, qrData) {

    switch (dataType) {
      case "reminder":
        this.props.reminderCreate({
          id, medName: qrData.medName, reminderTime: new Date(moment(qrData.reminderTime)),
          meal: qrData.meal, period: parseInt(qrData.period), dose: qrData.dose
        })
        this.setState({ addItemVisible: false, dataType: '', qrData: {} })
        break;
      case "appointment":
        this.props.appointmentCreate({
          id, doctorName: qrData.doctorName, date: new Date(moment(qrData.date)),
          place: qrData.place, time: moment().date(),
        })
        this.setState({ addItemVisible: false, dataType: '', qrData: {} })
        break;
    }




  }

}





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

export default connect(null, { reminderCreate, appointmentCreate })(AppCamera);