"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _reactNativeOrientation = _interopRequireDefault(require("react-native-orientation"));

var _reactNative = require("react-native");

var _react = _interopRequireWildcard(require("react"));

var _Colors = _interopRequireDefault(require("./Colors"));

var _reactNativeCamera = require("react-native-camera");

var _FontAwesome = _interopRequireDefault(require("react-native-vector-icons/FontAwesome"));

var _reactMoment = _interopRequireDefault(require("react-moment"));

var _geolocation = _interopRequireDefault(require("@react-native-community/geolocation"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _rnFetchBlob = _interopRequireDefault(require("rn-fetch-blob"));

var _ApiUrls = require("../Api/ApiUrls");

var _reactRedux = require("react-redux");

var _uploadImageDatasourceAction = require("../redux/actions/uploadImageDatasourceAction");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

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

const initial = _reactNativeOrientation.default.getInitialOrientation();

const leftFlex = 0.85;
const rightFlex = 0.15;
let SCREEN_WIDTH;
let SCREEN_HEIGHT;

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

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

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

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

    _defineProperty(this, "_orientationDidChange", orientation => {
      if (orientation === 'LANDSCAPE') {
        // do something with landscape layoutr
        SCREEN_HEIGHT = Math.round(_reactNative.Dimensions.get('window').height);
        SCREEN_WIDTH = Math.round(_reactNative.Dimensions.get('window').width);
      } else {
        // do something with portrait layout   
        SCREEN_HEIGHT = Math.round(_reactNative.Dimensions.get('window').width);
        SCREEN_WIDTH = Math.round(_reactNative.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() {
    _reactNativeOrientation.default.addOrientationListener(this._orientationDidChange);

    _reactNativeOrientation.default.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
      _reactNativeOrientation.default.lockToLandscapeLeft(); //make landscape

    } else {// do something else
    }
  }

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


    _reactNativeOrientation.default.removeOrientationListener(this._orientationDidChange);

    _geolocation.default.clearWatch(this.watchID); //For GeoLocation

  }

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

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

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

      if (isDir) {
        // Permission for storage
        const granted = await _reactNative.PermissionsAndroid.request(_reactNative.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.default.fs.writeFile(POSP + Image_Name, 'base64'); // let _copy = await RNFetchBlob.fs.cp(this.state.screenShotPath, POSP + Image_Name);

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

          _rnFetchBlob.default.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.default.fs.mkdir(POSP).catch(err => {
        console.log(err);
      });

      this.createFloder();
    }
  } //upload images


  uploadImage(activityId) {
    _rnFetchBlob.default.fetch('POST', _ApiUrls.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.default.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
    _reactNativeOrientation.default.lockToLandscapeLeft();

    _reactNativeOrientation.default.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.default.createElement(_reactNative.View, {
      style: {
        flex: 1,
        flexDirection: 'row'
      }
    }, /*#__PURE__*/_react.default.createElement(_reactNative.StatusBar, {
      hidden: true
    }), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: {
        flex: 1,
        flexDirection: 'row'
      }
    }, true && /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: {
        flex: leftFlex,
        backgroundColor: 'black'
      }
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Image, {
      source: {
        uri: this.state.finalWatermarkResult
      },
      style: styles.previewImageStyle
    })), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: [styles.previewImageIconMainView, {
        flex: rightFlex,
        backgroundColor: _Colors.default.greyBlack
      }]
    }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: {
        flex: 1
      }
    }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: styles.tickMarkImageView
    }, /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
      onPress: () => [this.props.navigation.navigate("DocumentCollection"), this.createFloder(activityId, activityTypeId)]
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Image, {
      source: tickMark,
      style: styles.tickMarkImageStyle
    }))), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
      style: styles.crossImageView
    }, /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
      onPress: () => this.props.navigation.navigate("Camera")
    }, /*#__PURE__*/_react.default.createElement(_reactNative.Image, {
      source: crossMark,
      style: styles.crossImageStyle
    })))))));
  }

}

const styles = _reactNative.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.default.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.default.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.default.digitYellow,
    left: 1
  },
  digitEdgeText: {
    position: 'absolute',
    fontSize: 20,
    color: _Colors.default.digitYellow,
    right: 1
  }
}); //Redux Action


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


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

var _default = (0, _reactRedux.connect)(mapReductStateToProps, mapDispatchToProps)(PreviewImage);

exports.default = _default;
//# sourceMappingURL=PreviewImage.js.map