import React, { useState, useEffect, useRef } from "react";
import { Text, View, TouchableOpacity } from "react-native";
import { Camera } from "expo-camera";
import {
  Ionicons,
  FontAwesome,
  MaterialCommunityIcons,
} from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/native";
import * as FileSystem from "expo-file-system";
import * as Permissions from "expo-permissions";
import * as MediaLibrary from "expo-media-library";

export default function ScreenCamera() {
  const navigation = useNavigation();
  const [hasPermission, setHasPermission] = useState(null);
  const [rollPermision, setRollPermission] = useState(null);
  const [type, setType] = useState(Camera.Constants.Type.back);
  const cameraRef = useRef(null);

  useEffect(() => {
    (async () => {
      //Ensure local photo direcotry exists.
      console.log(
        "ScreenCamera -> FileSystem.documentDirectory ",
        FileSystem.documentDirectory
      );

      await FileSystem.makeDirectoryAsync(
        FileSystem.documentDirectory + "photos"
      ).catch((e) => {
        console.log(e, "Directoryc already exists");
      });

      const { status } = await Camera.requestPermissionsAsync();
      setHasPermission(status === "granted");
      // camera roll
      const { cam_roll } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
      setRollPermission(cam_roll === "granted");
    })();
  }, []);

  const handleCameraType = () => {
    setType(
      type === Camera.Constants.Type.back
        ? Camera.Constants.Type.front
        : Camera.Constants.Type.back
    );
  };

  const handleTakePicture = async () => {
    console.log("Taking the picture!");
    if (cameraRef.current) {
      const options = {
        //quality: 0.5,
        //base64: true,
        //skipProcessing: true,
      };

      let photo = await cameraRef.current.takePictureAsync(options);
      console.log("ScreenCamera -> photo", photo);
      const filename = new Date().getTime() + ".jpg";

      await FileSystem.copyAsync({
        from: photo.uri,
        to: FileSystem.documentDirectory + "photos/" + filename,
      });

      console.log(
        "List of Files",
        await FileSystem.readDirectoryAsync(FileSystem.documentDirectory),
        await FileSystem.readDirectoryAsync(
          FileSystem.documentDirectory + "photos"
        )
      );
      //const asset = await MediaLibrary.createAssetAsync(photo.uri);
    }
  };

  if (hasPermission === null) {
    return <View />;
  }
  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }
  return (
    <View style={{ display: "flex", flex: 1 }}>
      <Camera style={{ flex: 1 }} type={type} ref={cameraRef}>
        <View
          style={{
            flex: 1,
            flexDirection: "row",
            justifyContent: "space-between",
            margin: 20,
          }}
        >
          <TouchableOpacity
            onPress={handleCameraType}
            style={{
              alignSelf: "flex-end",
              alignItems: "center",
              backgroundColor: "transparent",
            }}
          >
            <MaterialCommunityIcons
              name="camera-switch"
              style={{ color: "#fff", fontSize: 40 }}
            />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={handleTakePicture}
            style={{
              alignSelf: "flex-end",
              alignItems: "center",
              backgroundColor: "transparent",
            }}
          >
            <FontAwesome
              name="camera"
              style={{ color: "#fff", fontSize: 40 }}
            />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => {
              navigation.push("MediaCache");
            }}
            style={{
              alignSelf: "flex-end",
              alignItems: "center",
              backgroundColor: "transparent",
            }}
          >
            <Ionicons
              name="ios-photos"
              style={{ color: "#fff", fontSize: 40 }}
            />
          </TouchableOpacity>
        </View>
      </Camera>
    </View>
  );
}
