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,quality:0.1});
      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,quality:0.1 });
      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 () => {
    if (this.props.setpickimageSelfie == true) {
      let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: false, aspect: [4, 3], 
        quality: 0.1,
      });
      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")
      console.log("INI BASE 64 : "+ base64)
      //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")
    }
  }
  
  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);