import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Platform, } from 'react-native';
import { Camera } from 'expo-camera';
import * as Permissions from 'expo-permissions';
import { FontAwesome, Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import { connect } from 'react-redux';
import ActionType from '../redux/globalActionType';

class Cameras extends React.Component {
  state = {
    hasPermission: null,
    cameraType: Camera.Constants.Type.back,
    setReady: true,
    setImage: null,
  }

  async componentDidMount() {
    this.getPermissionAsync()
  }

  getPermissionAsync = async () => {
    // Camera roll Permission 
    if (Platform.OS === 'ios') {
      const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
      if (status !== 'granted') {
        alert('Sorry, we need camera roll permissions to make this work!');
      }
    }
    // Camera Permission
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({ hasPermission: status === 'granted' });
  }

  handleCameraType = () => {
    const { cameraType } = this.state
    this.setState({
      cameraType:
        cameraType === Camera.Constants.Type.back
          ? Camera.Constants.Type.front
          : Camera.Constants.Type.back
    })
  }

  capture() {
    if (this.props.selfie === true) {
      this.handleTakePictureSelfie()
    } else {
      this.handleTakePictureIdcard()
    }
  }

  pickImage = async () => {
    if (this.props.setpickimageSelfie == true) {
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
      });
      let resultImagePicker = result.uri
      // const base64 = await FileSystem.readAsStringAsync(resultImagePicker, { encoding: 'base64' });
      let UriProps = {
        URI: resultImagePicker,
      }
      let setpickSelfie = {
        setpickimageSelfie: false
      }
      this.props.setUriSelfi(UriProps);
      this.props.setpickimageSelfieProps(setpickSelfie);
      this.props.navigation.navigate("Upgrade Premium")

      //false
    } else {
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images
      });
      let resultImagePicker = result.uri
      // const base64 = await FileSystem.readAsStringAsync(resultImagePicker, { encoding: 'base64' });
      let UriPropsID = {
        URI_IDCARD: resultImagePicker,
      }
      let setpickSelfie = {
        setpickimageSelfie: true
      }
      this.props.setUriID(UriPropsID);
      this.props.setpickimageSelfieProps(setpickSelfie);
      this.props.navigation.navigate("Upgrade Premium")
    }
  }

  handleTakePictureSelfie = async () => {
    if (this.camera) {
      const options = { quality: 1 };
      const data = await this.camera.takePictureAsync(options);

      let UriProps = {
        URI: data.uri,
      }
      this.props.setUriSelfi(UriProps);
      this.props.navigation.navigate("Upgrade Premium")
    }
  }

  handleTakePictureIdcard = async () => {
    if (this.camera) {
      const options = { quality: 1 };
      const data = await this.camera.takePictureAsync(options);
      let UriProps = {
        URI_IDCARD: data.uri,
      }
      this.props.setUriID(UriProps);
      this.props.navigation.navigate("Upgrade Premium")
    }
  }

  render() {
    const { hasPermission } = this.state
    if (hasPermission === null) {
      return <View />;
    } else if (hasPermission === false) {
      return <Text>No access to camera</Text>;
    } else {
      return (
        <View style={{ flex: 1 }}>
          <Camera style={{ flex: 1 }} type={this.state.cameraType} ref={ref => { this.camera = ref }}>
            <View style={{ flex: 1, flexDirection: "row", justifyContent: "space-between", margin: 30 }}>
              <TouchableOpacity
                style={{
                  alignSelf: 'flex-end',
                  alignItems: 'center',
                  backgroundColor: 'transparent'
                }}
                onPress={() => this.pickImage()}>
                <Ionicons
                  name="ios-photos"
                  style={{ color: "#fff", fontSize: 40 }}
                />
              </TouchableOpacity>
              <TouchableOpacity
                style={{
                  alignSelf: 'flex-end',
                  alignItems: 'center',
                  backgroundColor: 'transparent',
                }}
                onPress={() => this.capture()}
              >
                <FontAwesome
                  name="camera"
                  style={{ color: "#fff", fontSize: 40 }}
                />
              </TouchableOpacity>
              <TouchableOpacity
                style={{
                  alignSelf: 'flex-end',
                  alignItems: 'center',
                  backgroundColor: 'transparent',
                }}
                onPress={() => this.handleCameraType()}
              >
                <MaterialCommunityIcons
                  name="camera-switch"
                  style={{ color: "#fff", fontSize: 40 }}
                />
              </TouchableOpacity>
            </View>
          </Camera>
        </View>
      );
    }
  }

}

const mapDispatchToProps = (dispacth) => {
  return {
    setUriSelfi: (UriProps) => dispacth({
      type: ActionType.SET_CHANGE_URI_SELFI,
      data: {
        URI: UriProps.URI,
        BASE64_SELFIE: UriProps.BASE64_SELFIE
      }
    }),
    setUriID: (UriPropsID) => dispacth({
      type: ActionType.SET_CHANGE_URI_ID,
      data: {
        URI_IDCARD: UriPropsID.URI_IDCARD,
        BASE64_ID: UriPropsID.BASE64_ID,
      }
    }),
    setpickimageSelfieProps: (setpickSelfie) => dispacth({
      type: ActionType.SET_PICKIMAGE,
      data: {
        setpickimageSelfie: setpickSelfie.setpickimageSelfie
      }
    }),
  }
}

const mapStateToProps = (state) => {
  return {
    URI: state.URI,
    URI_IDCARD: state.URI_IDCARD,
    img64: state.img64,
    id_card64: state.id_card64,
    selfie: state.selfie,
    idcard: state.id_card,
    setpickimageSelfie: state.setpickimageSelfie
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Cameras);



// takePictureSelfie = async () => {
//   if (this.camera) {
//     let photo = await this.camera.takePictureAsync({ skipProcessing: true, quality: 0 });

//     const manipResult = await ImageManipulator.manipulateAsync(
//       photo.uri,
//       [{ resize : {width:2000,height:1000}  }, { flip: ImageManipulator.FlipType.Vertical }],
//       { compress: 0.7, format:'jpeg' }
//     );
//     this.setState({
//       setImage:manipResult,
//     })

//     let UriProps = {
//       URI: this.state.setImage,
//       // BASE64_SELFIE:photo
//     }
//     this.props.setUriSelfi(UriProps);
//     this.props.navigation.navigate("Upgrade Premium")

//   }
// }


// takePictureIdCard = async () => {
//   if (this.camera) {
//     let photo = await this.camera.takePictureAsync({ skipProcessing: true, quality: 0 });

//     const manipResult = await ImageManipulator.manipulateAsync(
//       photo.uri,
//       [{ resize : {width:2000,height:1000}  }, { flip: ImageManipulator.FlipType.Vertical }],
//       { compress: 0.7, format:'jpeg' }
//     );
//     this.setState({
//       setImage:manipResult,
//     })

//     let UriProps = {
//       URI_IDCARD: this.state.setImage,
//       // BASE64_SELFIE:photo
//     }
//     this.props.setUriSelfi(UriProps);
//     this.props.navigation.navigate("Upgrade Premium")

//   }
// }