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 * as FileSystem from 'expo-file-system';
import { connect } from 'react-redux';
import ActionType from '../redux/globalActionType';

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

  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(){
    // console.log('IS SELFIE : ' + this.props.selfie)
    // console.log('IS IDCARD : ' + this.props.idcard)
    if (this.props.selfie === true) {
      this.takePictureSelfie()
      // console.log('ini foto selfie');
    } else {
      this.takePictureIdCard()
      // console.log('ini foto ktp');
    }
  }

  takePictureSelfie = async () => {
    if (this.camera) {
      let photo = await this.camera.takePictureAsync({skipProcessing:true});
      let photo_img = photo.uri;
      const base64 = await FileSystem.readAsStringAsync(photo_img, { encoding: 'base64' });
      // var set_photo = photo.replace('uri','')
      let UriProps = {
        URI: photo_img,
        // BASE64_SELFIE:photo
      }
      this.props.setUriSelfi(UriProps);
      this.props.navigation.navigate("Upgrade Premium")
      // console.log(photo);
      // console.log("ini sudah di pencet" + photo_img)
    }
  }

  takePictureIdCard = async () => {
    if (this.camera) {
      let photo = await this.camera.takePictureAsync({skipProcessing:true});
      let photo_img = photo.uri;
      const base64 = await FileSystem.readAsStringAsync(photo_img, { encoding: 'base64' });
      // var set_photo = photo.replace('uri','')
      let UriPropsID = {
        URI_IDCARD: photo_img,
        // BASE64_ID: photo
      }
      this.props.setUriID(UriPropsID);
      this.props.navigation.navigate("Upgrade Premium")
      // console.log("ini sudah di pencet" + photo_img)
    }
  }

  

  pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images
    });
  }

  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,
        }
    }),
  }
}

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

  }
}

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










































// import React, { useState, useEffect } from 'react';
// import { Text, View, TouchableOpacity } from 'react-native';
// import { Camera } from 'expo-camera';

// export default function Cameras() {
//   const [hasPermission, setHasPermission] = useState(null);
//   const [type, setType] = useState(Camera.Constants.Type.back);

//   useEffect(() => {
//     (async () => {
//       const { status } = await Camera.requestPermissionsAsync();
//       setHasPermission(status === 'granted');
//     })();
//   }, []);

//   if (hasPermission === null) {
//     return <View />;
//   }
//   if (hasPermission === false) {
//     return <Text>No access to camera</Text>;
//   }
//   return (
//     <View style={{ flex: 1 }}>
//       <Camera style={{ flex: 1 }} type={type}>
//         <View
//           style={{
//             flex: 1,
//             backgroundColor: 'transparent',
//             flexDirection: 'row',
//           }}>
//           <TouchableOpacity
//             style={{
//               flex: 0.1,
//               alignSelf: 'flex-end',
//               alignItems: 'center',
//             }}
//             onPress={() => {
//               setType(
//                 type === Camera.Constants.Type.back
//                   ? Camera.Constants.Type.front
//                   : Camera.Constants.Type.back
//               );
//             }}>
//             <Text style={{ fontSize: 18, marginBottom: 10, color: 'white' }}> Flip </Text>
//           </TouchableOpacity>
//         </View>
//       </Camera>
//     </View>
//   );
// }