function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

import Orientation from 'react-native-orientation';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, TextInput, StatusBar, FlatList, Alert, PermissionsAndroid, ToastAndroid, Platform, Dimensions, ActivityIndicator } from 'react-native';
import React, { Component } from 'react';
import { Image } from 'react-native';
import Colors from './Colors';
import { RNCamera } from 'react-native-camera';
import Icon from 'react-native-vector-icons/FontAwesome';
import moment from 'react-moment';
import Geolocation from '@react-native-community/geolocation';
import PropTypes from 'prop-types';
import RNFetchBlob from 'rn-fetch-blob';
import { INSTRUCTIONS_URL, SELFSURVEYSERVICE_DOCUMENT_URL, AGENT_DATA } from '../Api/ApiUrls';
import { connect } from 'react-redux';
import { addUploadImageDatasource } from '../redux/actions/uploadImageDatasourceAction';
const initial = Orientation.getInitialOrientation();
const leftFlex = 0.85;
const rightFlex = 0.15;
let SCREEN_WIDTH;
let SCREEN_HEIGHT;

if (initial === 'PORTRAIT') {
  SCREEN_HEIGHT = Math.round(Dimensions.get('window').height);
  SCREEN_WIDTH = Math.round(Dimensions.get('window').width);
} else {
  SCREEN_HEIGHT = Math.round(Dimensions.get('window').width);
  SCREEN_WIDTH = Math.round(Dimensions.get('window').height);
}

const crossMark = require('./Image/crossMark.png');

const tickMark = require('./Image/tickMark.png');

class PreviewImage extends Component {
  constructor(props) {
    super(props);

    _defineProperty(this, "_orientationDidChange", orientation => {
      if (orientation === 'LANDSCAPE') {
        // do something with landscape layoutr
        SCREEN_HEIGHT = Math.round(Dimensions.get('window').height);
        SCREEN_WIDTH = Math.round(Dimensions.get('window').width);
      } else {
        // do something with portrait layout   
        SCREEN_HEIGHT = Math.round(Dimensions.get('window').width);
        SCREEN_WIDTH = Math.round(Dimensions.get('window').height);
      }
    });

    this.state = {
      isDisplayQuoteInstruction: true,
      isWithQuote: true,
      isWithOutQuote: false,
      isDisplayInstruction: false,
      torchon: '',
      isDisplayCameraPreview: false,
      isDisplayCamera: false,
      flashState: true,
      //for flash
      dateAndTime: '',
      //date and time
      currentLongitude: 'unknown',
      //Initial Longitude
      currentLatitude: 'unknown',
      //Initial Latitude
      isDisplayVideoRecorder: false,
      fullDataSource: '',
      assets: '',
      headerShown: false,
      dataSource: '',
      cameraState: '',
      buttonText: '',
      skipdata: '',
      isBackButtonPressed: false,
      isSkipButtonPressed: false,
      screenShotPath: '',
      isDisplayUploadDocument: false,
      upLoadIamgeDataSource: [],
      documentUploadPercentage: 0,
      odometerReading: '',
      ANDROID_ID: '',
      CurrentDate: '',
      showError: false,
      isLoading: true,
      registrationNumber: '',
      isSelected: false,
      isFocused: false,
      finalWatermarkResult: this.props.navigation.state.params.finalWatermarkResult,
      count: this.props.navigation.state.params.count,
      productImage: this.props.navigation.state.params.productImage,
      extention: this.props.navigation.state.params.extention,
      stepTitle: this.props.navigation.state.params.stepTitle,
      instructionData: this.props.navigation.state.params.instructionData
    };
  }

  componentDidMount() {
    Orientation.addOrientationListener(this._orientationDidChange);
    Orientation.lockToLandscapeLeft();
  }

  componentWillMount() {
    // The getOrientation method is async. It happens sometimes that
    // you need the orientation at the moment the JS runtime starts running on device.
    // `getInitialOrientation` returns directly because its a constant set at the
    // beginning of the JS runtime.
    if (initial === 'PORTRAIT') {
      // do something
      Orientation.lockToLandscapeLeft(); //make landscape
    } else {// do something else
    }
  }

  componentWillUnmount() {
    Orientation.getOrientation((err, orientation) => {
      console.log(`Current Device Orientation: ${orientation}`); //display currrent location state
    }); // Remember to remove listener

    Orientation.removeOrientationListener(this._orientationDidChange);
    Geolocation.clearWatch(this.watchID); //For GeoLocation
  }

  //create floder if not preaent
  async createFloder(activityId, activityTypeId) {
    const POSP = RNFetchBlob.fs.dirs.SDCardDir + '/POSP/'; //Create Floder in External storage

    this.setState({
      FilePath: POSP
    });
    let exists = await RNFetchBlob.fs.exists(POSP); // checkExist 

    if (exists) {
      let isDir = await RNFetchBlob.fs.isDir(POSP);

      if (isDir) {
        // Permission for storage
        const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, {
          title: 'Read Internal Storage',
          message: 'Read Internal Storage',
          buttonPositive: 'Ok',
          buttonNegative: 'Cancle'
        });

        if (granted) {
          // if Granted
          console.log("Image Name = " + this.state.productImage);
          const Image_Name = activityId + "_" + this.state.productImage + this.state.extention; //Image NAme with Extension

          this.setState({
            imageName: Image_Name
          });
          await RNFetchBlob.fs.writeFile(POSP + Image_Name, 'base64'); // let _copy = await RNFetchBlob.fs.cp(this.state.screenShotPath, POSP + Image_Name);

          let _copy = await RNFetchBlob.fs.cp(this.state.finalWatermarkResult, POSP + Image_Name);

          RNFetchBlob.fs.stat(this.state.FilePath + this.state.imageName).then(stats => {
            console.log("FileName: " + stats.filename);
            console.log("FileSize: " + stats.size);
            console.log("type: " + stats.type);
            console.log("lastModified: " + stats.lastModified);
            this.setState({
              fileSize: stats.size
            });
          }).catch(err => {});
          this.uploadImage(activityId, activityTypeId);
        } else {
          // ask Permission
          this.createFloder();
        }
      }
    } else {
      //IF not then create floder
      RNFetchBlob.fs.mkdir(POSP).catch(err => {
        console.log(err);
      });
      this.createFloder();
    }
  } //upload images


  uploadImage(activityId) {
    RNFetchBlob.fetch('POST', SELFSURVEYSERVICE_DOCUMENT_URL, {
      'Content-Type': 'multipart/form-data'
    }, [// element with property `filename` will be transformed into `file` in form data
    //file name is Original file name
    {
      name: 'file',
      filename: this.state.imageName,
      type: 'image/jpg',
      data: RNFetchBlob.wrap(this.state.FilePath + this.state.imageName)
    }, {
      name: 'documentData',
      data: JSON.stringify({
        "activityId": activityId,
        "documentSource": "DigitEdge",
        "geoLocation": {
          "deviceIMEI": "358057081601559",
          "deviceName": "SM-G950F",
          "deviceTime": 1600362315847,
          "documentSource": "DigitEdge",
          "ipAddress": "192.168.1.10",
          "isBlocked": false,
          "latitude": "18.6028985",
          "longitude": "73.9113947",
          "macAddress": "30:07:4D:F7:C4:B8",
          "operatingSystem": "9",
          "timezone": "Asia/Kolkata"
        },
        "isLast": false,
        "isLastData": false,
        "isLastDocument": false,
        "isSurveyor": false,
        "manualOdometerReading": "",
        "source": "DIGITEDGE"
      })
    }]).uploadProgress({
      interval: 0.5
    }, (written, total) => {
      console.log('Written', written);
      console.log('total', total);
      console.log('uploaded', written / total);
      this.setState({
        documentUploadPercentage: written / total
      }); //condition for when display documentUpload Screeen 

      if (this.state.count == this.state.instructionData.length - 1) {
        // if (this.state.count == 1) {
        setTimeout(() => {
          this.props.navigation.navigate("DocumentUpload", {
            upLoadIamgeDataSource: this.state.upLoadIamgeDataSource
          });
        }, 200);
      }
    }) //FOR DOWNLOAD
    // listen to download progress event, every 10%
    // .progress({ count: 10 }, (received, total) => {
    //     console.log('progress', received / total)
    //     // let isExisist = this.state.upLoadIamgeDataSource.find(this.state.upLoadIamgeDataSource.stepTitle == this.state.instructionData[this.state.count - 1].stepTitle)
    //     // if (this.state.count == this.state.instructionData.length) {
    //     //     // if (this.state.count == 1) {
    //     //     this.props.navigation.navigate("DocumentUpload", { upLoadIamgeDataSource: this.state.upLoadIamgeDataSource })
    //     // }
    // })
    .then(response => {
      console.log("******************** resp: " + JSON.stringify(response)); //Data to redux

      this.props.addUploadImageDatasource({
        imagePath: 'file://' + this.state.FilePath + this.state.imageName,
        stepTitle: this.state.stepTitle,
        imageSize: this.state.fileSize,
        upLoadStatus: this.state.documentUploadPercentage
      });
    }).catch(err => {
      console.log("******************** err: " + JSON.stringify(err));
    });
  }

  render() {
    //   For Landsccape
    Orientation.lockToLandscapeLeft();
    Orientation.addOrientationListener(this._orientationDidChange);
    const activityId = this.props.screenProps.activityId;
    const activityTypeId = this.props.screenProps.activityTypeId;
    console.log("ActivityId From App := " + activityId);
    console.log("activityTypeId From App := " + activityTypeId);
    return /*#__PURE__*/React.createElement(View, {
      style: {
        flex: 1,
        flexDirection: 'row'
      }
    }, /*#__PURE__*/React.createElement(StatusBar, {
      hidden: true
    }), /*#__PURE__*/React.createElement(View, {
      style: {
        flex: 1,
        flexDirection: 'row'
      }
    }, true && /*#__PURE__*/React.createElement(View, {
      style: {
        flex: leftFlex,
        backgroundColor: 'black'
      }
    }, /*#__PURE__*/React.createElement(Image, {
      source: {
        uri: this.state.finalWatermarkResult
      },
      style: styles.previewImageStyle
    })), /*#__PURE__*/React.createElement(View, {
      style: [styles.previewImageIconMainView, {
        flex: rightFlex,
        backgroundColor: Colors.greyBlack
      }]
    }, /*#__PURE__*/React.createElement(View, {
      style: {
        flex: 1
      }
    }, /*#__PURE__*/React.createElement(View, {
      style: styles.tickMarkImageView
    }, /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: () => [this.props.navigation.navigate("DocumentCollection"), this.createFloder(activityId, activityTypeId)]
    }, /*#__PURE__*/React.createElement(Image, {
      source: tickMark,
      style: styles.tickMarkImageStyle
    }))), /*#__PURE__*/React.createElement(View, {
      style: styles.crossImageView
    }, /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: () => this.props.navigation.navigate("Camera")
    }, /*#__PURE__*/React.createElement(Image, {
      source: crossMark,
      style: styles.crossImageStyle
    })))))));
  }

}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    flexDirection: 'row'
  },
  productImageView: {
    flex: 0.475
  },
  blankView: {
    flex: 0.05
  },
  productInfoView: {
    flex: 0.475,
    marginRight: 16,
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT
  },
  headerView: {
    backgroundColor: '#C6AFFF',
    height: 40,
    justifyContent: 'center'
  },
  headerText: {
    marginLeft: 16,
    fontSize: 20,
    fontFamily: 'Muli-Black'
  },
  productImageStyle: {
    marginTop: 8,
    marginLeft: 16,
    marginBottom: 40,
    height: SCREEN_HEIGHT - 70
  },
  backButtonImageStyle: {
    marginLeft: 32,
    height: 24,
    width: 24,
    backgroundColor: 'red'
  },
  subHeaderText: {
    fontFamily: 'Mulli-Regular',
    fontSize: 16,
    marginLeft: 16
  },
  instructionText: {
    fontFamily: 'Mulli-Regular',
    fontSize: 16,
    marginLeft: 16,
    marginBottom: 20
  },
  captureImageButtonView: {
    height: 48,
    borderRadius: 4,
    backgroundColor: Colors.digitYellow,
    marginTop: 2,
    flexDirection: 'row',
    justifyContent: 'center'
  },
  captureImageButtonText: {
    fontSize: 16,
    fontFamily: 'Muli-Black',
    alignSelf: 'center'
  },
  container: {
    flex: 1 // flexDirection: 'row',
    // backgroundColor: 'black',

  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center'
  },
  capture: {
    flex: 0,
    backgroundColor: '#fff',
    borderRadius: 5,
    padding: 15,
    paddingHorizontal: 20,
    alignSelf: 'flex-end',
    margin: 20,
    position: 'absolute'
  },
  flash: {
    flex: 0,
    backgroundColor: '#fff',
    borderRadius: 5,
    padding: 15,
    paddingHorizontal: 20,
    alignSelf: 'flex-end',
    margin: 20,
    position: 'absolute'
  },
  previewImageStyle: {
    width: SCREEN_HEIGHT,
    height: SCREEN_WIDTH
  },
  dateAndTimeText: {
    position: 'absolute',
    fontSize: 20,
    color: Colors.digitYellow,
    left: 1,
    bottom: 1
  },
  previewImageIconMainView: {
    justifyContent: 'flex-end',
    backgroundColor: 'black',
    flexDirection: 'column'
  },
  tickMarkImageView: {
    flex: 0.7,
    justifyContent: 'flex-end',
    paddingBottom: 50,
    alignSelf: 'center'
  },
  tickMarkImageStyle: {
    width: 70,
    height: 70
  },
  crossImageView: {
    flex: 0.3,
    alignSelf: 'center'
  },
  crossImageStyle: {
    width: 70,
    height: 70
  },
  cameraIconView: {
    flexDirection: 'row',
    justifyContent: 'center',
    width: SCREEN_WIDTH,
    position: 'absolute'
  },
  infoScrollView: {
    marginTop: 40,
    height: SCREEN_HEIGHT - 200
  },
  subHeaderTextView: {
    height: 40,
    marginTop: 8
  },
  backButtonImageView: {
    backgroundColor: '#C6AFFF',
    height: 40,
    justifyContent: 'center',
    marginLeft: 16
  },
  latLongText: {
    position: 'absolute',
    fontSize: 20,
    color: Colors.digitYellow,
    left: 1
  },
  digitEdgeText: {
    position: 'absolute',
    fontSize: 20,
    color: Colors.digitYellow,
    right: 1
  }
}); //Redux Action

const mapDispatchToProps = dispatch => {
  return {
    addUploadImageDatasource: uploadImageDatasource => dispatch(addUploadImageDatasource(uploadImageDatasource))
  };
}; //Redux State


const mapReductStateToProps = reduxState => {
  const {
    UploadImageData
  } = reduxState;
  return {
    UploadImageData
  };
};

export default connect(mapReductStateToProps, mapDispatchToProps)(PreviewImage);
//# sourceMappingURL=PreviewImage.js.map