import { useState } from 'react';
import { Alert, Linking } from 'react-native';
import { launchImageLibrary, launchCamera } from 'react-native-image-picker';
import { isValidImageType } from '../utils';
import { useCameraPermission } from './usePermissions';
import { deleteAmityFile } from '../../core/legacy/file';
import { useUpload } from '../../core/hooks';
const useImagePicker = () => {
  const {
    getCameraPermission
  } = useCameraPermission();
  const [progress, setProgress] = useState(0);
  const [imageUri, setImageUri] = useState(null);
  const [uploadedImage, setUploadedImage] = useState(null);
  const {
    uploadImage,
    isImageUploading
  } = useUpload();
  const uploadFileToAmity = async path => {
    try {
      setImageUri(path);
      const {
        data
      } = await uploadImage({
        file: path,
        onProgress: setProgress
      });
      setUploadedImage(data[0]);
      setProgress(0);
      return data[0];
    } catch (error) {
      return null;
    } finally {
      setProgress(0);
    }
  };
  const openImageGallery = async options => {
    const result = await launchImageLibrary(options);
    if (!result.didCancel && result.assets && result.assets.length > 0) {
      var _result$assets$, _result$assets$2;
      if (!isValidImageType((_result$assets$ = result.assets[0]) === null || _result$assets$ === void 0 ? void 0 : _result$assets$.type)) {
        return Alert.alert('Unsupported image type', 'Please upload a PNG or JPG image.', [{
          text: 'OK'
        }]);
      }
      return uploadFileToAmity((_result$assets$2 = result.assets[0]) === null || _result$assets$2 === void 0 ? void 0 : _result$assets$2.uri);
    }
  };
  const openCamera = async options => {
    const cameraPermission = await getCameraPermission();
    if (!cameraPermission) return Linking.openSettings();
    const result = await launchCamera(options);
    if (!result.didCancel && result.assets && result.assets.length > 0) {
      var _result$assets$3, _result$assets$4;
      if (!isValidImageType((_result$assets$3 = result.assets[0]) === null || _result$assets$3 === void 0 ? void 0 : _result$assets$3.type)) {
        return Alert.alert('Unsupported image type', 'Please upload a PNG or JPG image.', [{
          text: 'OK'
        }]);
      }
      return uploadFileToAmity((_result$assets$4 = result.assets[0]) === null || _result$assets$4 === void 0 ? void 0 : _result$assets$4.uri);
    }
  };
  const removeSelectedImage = () => {
    setProgress(0);
    setImageUri(null);
    setUploadedImage(null);
    deleteAmityFile(uploadedImage === null || uploadedImage === void 0 ? void 0 : uploadedImage.fileId);
  };
  return {
    isLoading: isImageUploading,
    imageUri,
    progress,
    uploadedImage,
    removeSelectedImage,
    openImageGallery,
    openCamera
  };
};
export default useImagePicker;
//# sourceMappingURL=useImagePicker.js.map