text: /**
   * @Author: Harsha Attray <harsha>
   * @Date:   2017-08-17T18:15:36+05:30
   * @Project: Retailstore-Attendance-Monitor
   * @Filename: upload.js
   * @Last modified by:   harsha
   * @Last modified time: 2017-08-22T15:32:33+05:30
   * @License: Apache License v2.0
   */
  
  import React, { Component } from 'react';
  /*superagent for network requests*/
  import superagent from 'superagent';
  /*sha1  js function for hashing messages with the SHA-1 algorithm*/
  import sha1 from 'sha1';
  import firebase from 'firebase';
  /*State traversal workhorse function for route traversal*/
  import { Actions } from 'react-native-router-flux';
  
  /*react-native-dotenv extracts keys defined in .env file.
  Here we import Cloudinary Credentials and keys*/
  import {
    CLOUDINARY_CLOUDNAME,
    CLOUDINARY_API_SECRET,
    CLOUDINARY_API_KEY,
    CLOUDINARY_UPLOAD_PRESET
  } from 'react-native-dotenv';
  
  import { Text, View, Alert, Image, ScrollView } from 'react-native';
  /*Importing Common UI-components*/
  import { Card, Button, CardSection, Loader } from '../common/';
  
  /*Upload Screen Component*/
  export default class UploadRequest extends Component {
    /* Defining state variables which can be manipulated later*/
    state = {
      uploadLoader: false,
    };
    /*uploadImage Function with Cloudinary upload request along with image encoding and
    data retrieval from cloudinary*/
    uploadImage(text) {
      /* Defining state variable(s) which can be manipulated later*/
      this.setState({
        uploadLoader: true,
      });
      /*Accessing the image url generated from AttendanceCam Component and passed
       on to this view via Actions function*/
      const SavedImage = this.props.SavedImage;
      /*Cloudinary API request URL with with params*/
      const url = 'https://api.cloudinary.com/v1_1/' + CLOUDINARY_CLOUDNAME + '/image/upload';
      /*timestamp generated using standard Date function*/
      const timestamp = Date.now() / 1000;
      /*Cloudinary preset generated from Cloudinary accessed from .env*/
      const uploadPreset = CLOUDINARY_UPLOAD_PRESET;
      /*combining params together into a single constant*/
      const paramsBlock = 'timestamp=' + timestamp + '&upload_preset=' + uploadPreset +
      CLOUDINARY_API_SECRET;
     /*generating a unique signature each time an upload is attempted using the
     sha1 keys combining the credentials in the  paramsBlock*/
      const signature = sha1(paramsBlock);
      /*params Object with necessary data to be passed onto Cloudinary via the API call*/
      const params = {
        api_key: CLOUDINARY_API_KEY,
        timestamp,
        upload_preset: uploadPreset,
        signature
      };
      /*uploadStream acts as a hook to which the file, and image uri,type,name objects are appended
      the attach call is an upload request to Cloudinary
       */
      const uploadStream = superagent.post(url);
      uploadStream.attach('file', { uri: SavedImage, type: 'image/png', name: 'upload.png' });
      Object.keys(params).forEach((key) => {
        uploadStream.field(key, params[key]);
      });
      /*uploadStream 'end' results in a response object from cloudinary on success*/
      uploadStream.end((err, res) => {
        /*The response data is parsed and relavant attribute are extracted*/
        const parseTextBody = JSON.parse(res.text);
        const createdAt = parseTextBody["created_at"];
        const createdAtDate = new Date(createdAt);
        const imageurl = parseTextBody["secure_url"];
        const date = createdAtDate.toString();
        const schedule = text;
        if (err) {
          alert(err);
          return;
        }
        else if (res) {
          /*In cas of a successful upload the uploadLoader loading state is set to false*/
          this.setState({
            uploadLoader: false
          });
          /*The alert dialog is an important component here. The main uploadToDb() i.e,
          the firebase data upload call is exexuted here onPress 'OK',
          There is a cancel option incase the user wants tp go back and re-capture the image*/
          Alert.alert(
            'Upload Successful',
            'Sending Credentials',
            [
              { text: 'OK',
                onPress: this.uploadToDb.bind(this, date, imageurl, schedule)
              },
            ],
            { cancelable: false }
          );
          return;
        }
        // console.log(JSON.stringify(res.body));
      });
    }
  
  /*uploadToDb)() function executes  a FirebaseDB  write call with an upload path and params */
    uploadToDb(date, imageurl, schedule) {
      /*This fetches the currentUser details from firebase.
      We use this to extract the uid(unique id  generated by firebase for each user) */
      const { currentUser } = firebase.auth();
      /*the streetName variable is updated with the reverse geocoded data passed on from the
      AttendanceCam view via Actions(). These are accessed via props*/
      const streetName = this.props.streetName;
      /*the locality variable is updated with the reverse geocoded data passed on from the
      AttendanceCam view via Actions(). These are accessed via props*/
      const locality = this.props.locality;
      /*FirebaseDB upload call with the upload path.This is a custom path set to
      access employee records.Accessibility  of the data from this path is based
      on the DB rules set in the firebase console
      */
      firebase.database().ref(`/employees/records/${currentUser.uid}/`)
      .push({
        date, imageurl, streetName, locality, schedule
      });
      /*Upon success, the Actions() based scene traversal takes over and the user is
      directed to successView
      */
      Actions.successView();
    }
    uploadStatus() {
      /*renders the check-in and Check-Out buttons with the uploadImage() function call
      each button takes in a requisite text param that is passed on based on the kind of
      attendance check the user is attempting
      */
      if (this.state.uploadLoader) {
        return <Loader size='small' />;
      }
      return (
        <View>
          <Card>
            <CardSection>
              <Button onPress={this.uploadImage.bind(this, 'Check-In')}>Check-In</Button>
            </CardSection>
          </Card>
          <Card style={{ paddingTop: 300 }}>
            <CardSection styles={{ paddingTop: 100 }}>
              <Button onPress={this.uploadImage.bind(this, 'Check-Out')}>Check-Out</Button>
            </CardSection>
          </Card>
        </View>
      );
    }
    checkAttendance() {
      /*checkAttendance() is a status watcher function that shows the user their last
      attendance update if any*/
      if (this.props.checkTime) {
        /*Inline styled components to show the time and the kind of attendance that
        the user has uploaded previously*/
        const B = (props) => <Text style={{ color: 'green' }}>{ this.props.checkTime}</Text>;
        const S = (props) => <Text style={{ color: 'red' }}>{ this.props.checkSchedule}</Text>;
        //    const T = (props) => <Text style={{ color: 'orange' }}>
        //    Last attendance submitted at
        //  </Text>;
  
        return (
          <CardSection style={styles.cardSectionStyle}>
            <Text style={styles.textStyle}>
              Last attendance submitted at : {"\n"} <B></B>  {"\n"} Check-Type: <S></S> {"\n"}
              Please select one of the choices below to submit your attendance
            </Text>
          </CardSection>
        );
      }
      return (
        <CardSection style={styles.cardSectionStyle}>
          <Text style={styles.textStyle}>
            Please select one of the choices below to submit your attendance
          </Text>
        </CardSection>
      );
    }
    render() {
      return (
        <ScrollView>
          <View>
            <View style={styles.logoContainer}>
              <Image source={require('../../Images/icon.png')} />
            </View>
            {this.checkAttendance()}
            {this.uploadStatus()}
          </View>
        </ScrollView>
      );
    }
  }
  
  
  const styles = {
    cardSectionStyle: {
      justifyContent: 'center'
    },
    logoContainer: {
      alignItems: 'center',
      flexGrow: 1,
      justifyContent: 'center'
    },
    textStyle: {
      flex: 1,
      fontSize: 18,
      textAlign: 'center',
      lineHeight: 40,
      paddingTop: 50,
      paddingBottom: 50
    },
  };
  