import { SCREEN_HEIGHT, SCREEN_WIDTH } from './Constants';
import Orientation from 'react-native-orientation';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, StatusBar, PermissionsAndroid } 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 VideoPlayer from 'react-native-video-player';
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 crossMark = require('./Image/crossMark.png');

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

class VideoPreview extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isDisplayQuoteInstruction: true,
      isWithQuote: true,
      isWithOutQuote: false,
      isDisplayInstruction: false,
      torchon: '',
      isDisplayCameraPreview: false,
      isDisplayCamera: false,
      localPath: '',
      flashState: true,
      //for flash
      dateAndTime: '',
      //date and time
      currentLongitude: 'unknown',
      //Initial Longitude
      currentLatitude: 'unknown',
      //Initial Latitude
      isDisplayVideoRecorder: false,
      instructionData: '',
      fullDataSource: '',
      assets: '',
      headerShown: false,
      count: 0,
      dataSource: '',
      cameraState: '',
      buttonText: '',
      skipdata: '',
      isBackButtonPressed: false,
      isSkipButtonPressed: false,
      extention: '',
      screenShotPath: '',
      isDisplayUploadDocument: false,
      upLoadIamgeDataSource: [],
      documentUploadPercentage: 0,
      odometerReading: '',
      ANDROID_ID: '',
      CurrentDate: '',
      showError: false,
      isLoading: true,
      registrationNumber: '',
      isSelected: false,
      isFocused: false,
      staincil: this.props.navigation.state.params.staincil,
      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,
      localPath: this.props.navigation.state.params.localPath
    };
  }

  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.localPath, 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) {
    const documentUploadData = {
      "activityId": activityId,
      "documentSource": "DigitEdge",
      "geoLocation": {
        "deviceIMEI": this.state.ANDROID_ID,
        "deviceName": this.state.DEVICE_NAME,
        "deviceTime": this.state.CurrentDate,
        "documentSource": "DigitEdge",
        "ipAddress": this.state.IP,
        "isBlocked": false,
        "latitude": this.state.currentLatitude,
        "longitude": this.state.currentLongitude,
        "macAddress": this.state.MAC,
        "operatingSystem": this.state.VERSION,
        "timezone": "Asia/Kolkata"
      },
      "isLast": false,
      "isLastData": false,
      "isLastDocument": false,
      "isSurveyor": false,
      "manualOdometerReading": "",
      "source": "DIGITEDGE"
    };
    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: this.state.FilePath + this.state.imageName
    }, {
      name: 'documentData',
      data: JSON.stringify(documentUploadData)
    }]).uploadProgress({
      interval: 250
    }, (written, total) => {
      console.log('Written', written);
      console.log('total', total);
      console.log('uploaded', written / total);
      this.setState({
        documentUploadPercentage: written / total
      });
      this.props.addUploadImageDatasource({
        imagePath: 'file://' + this.state.FilePath + this.state.imageName,
        stepTitle: this.state.stepTitle,
        imageSize: this.state.fileSize,
        upLoadStatus: this.state.documentUploadPercentage
      });
    }) // 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 - 1) {
        // if (this.state.count == 1) {
        this.props.navigation.navigate("DocumentUpload", {
          upLoadIamgeDataSource: this.state.upLoadIamgeDataSource
        });
      }
    }).then(response => {
      console.log("******************** resp: " + JSON.stringify(response));
    }).catch(err => {
      console.log("******************** err: " + JSON.stringify(err));
    });
  }

  render() {
    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, null, /*#__PURE__*/React.createElement(StatusBar, {
      hidden: true
    }), /*#__PURE__*/React.createElement(VideoPlayer, {
      video: {
        uri: this.state.localPath
      } // videoWidth={SCREEN_WIDTH}
      // videoHeight={SCREEN_HEIGHT}
      ,
      pauseOnPress: true,
      seekBarWidth: 5
    }), /*#__PURE__*/React.createElement(View, {
      style: {
        position: 'absolute',
        left: 10,
        bottom: 70
      }
    }, /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: () => this.props.navigation.navigate("VideoRecorder")
    }, /*#__PURE__*/React.createElement(Text, {
      style: {
        backgroundColor: Colors.digitYellow,
        fontFamily: 'Muli-Black',
        paddingTop: 10,
        paddingBottom: 10,
        paddingLeft: 15,
        paddingRight: 15,
        borderRadius: 4
      }
    }, "RETRY"))), /*#__PURE__*/React.createElement(View, {
      style: {
        position: 'absolute',
        right: 10,
        bottom: 70
      }
    }, /*#__PURE__*/React.createElement(TouchableOpacity, {
      onPress: () => [this.props.navigation.navigate("DocumentCollection"), this.createFloder(activityId, activityTypeId)]
    }, /*#__PURE__*/React.createElement(Text, {
      style: {
        backgroundColor: Colors.digitYellow,
        fontFamily: 'Muli-Black',
        paddingTop: 10,
        paddingBottom: 10,
        paddingLeft: 15,
        paddingRight: 15,
        borderRadius: 4
      }
    }, "SUBMIT"))));
  }

}

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_WIDTH,
    height: SCREEN_HEIGHT
  },
  dateAndTimeText: {
    position: 'absolute',
    fontSize: 20,
    color: Colors.digitYellow,
    left: 1,
    bottom: 1
  },
  previewImageIconMainView: {
    flex: 0.05,
    backgroundColor: 'black'
  },
  tickMarkImageView: {
    flex: 0.6,
    justifyContent: 'flex-end'
  },
  tickMarkImageStyle: {
    width: 30,
    height: 30,
    backgroundColor: 'white',
    alignContent: 'flex-end',
    marginBottom: 20
  },
  crossImageView: {
    flex: 0.4,
    justifyContent: 'flex-end',
    marginBottom: 20
  },
  crossImageStyle: {
    width: 30,
    height: 30,
    backgroundColor: 'white',
    alignContent: 'flex-end'
  },
  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
  }
});

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


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

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