function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React from "react";
import { StyleSheet, View, FlatList, Dimensions, ActivityIndicator, Platform } from "react-native";
import _ from "lodash";
import * as ScreenOrientation from "expo-screen-orientation";
import * as MediaLibrary from "expo-media-library";
import { Camera } from "expo-camera";
import { isVideo } from "../../helper";
import ImageTile from "./ImageTile";
const {
  width
} = Dimensions.get("window");
const defaultSelectionLimit = 10;
const defaultLoadCount = 50;
export default class ImageBrowser extends React.Component {
  constructor(props) {
    super(props);
    _defineProperty(this, "isLocal", () => {
      return _.isNil(this.props.remoteAlbums);
    });
    _defineProperty(this, "getPermissionsAsync", async () => {
      const {
        status: camera
      } = await Camera.requestCameraPermissionsAsync();
      const {
        status: cameraRoll
      } = await MediaLibrary.requestPermissionsAsync();
      this.setState({
        hasCameraPermission: camera === "granted",
        hasCameraRollPermission: cameraRoll === "granted"
      });
    });
    _defineProperty(this, "onOrientationChange", ({
      orientationInfo
    }) => {
      ScreenOrientation.removeOrientationChangeListeners();
      ScreenOrientation.addOrientationChangeListener(this.onOrientationChange);
      const numColumns = this.getNumColumns(orientationInfo.orientation);
      this.setState({
        numColumns
      });
    });
    _defineProperty(this, "getNumColumns", orientation => orientation === ScreenOrientation.Orientation.PORTRAIT_UP || orientation === ScreenOrientation.Orientation.PORTRAIT_DOWN ? 4 : 7);
    _defineProperty(this, "isVideoSelected", () => {
      return this.state.selected.find(uri => {
        const photo = this.state.photos.find(photo => photo.uri === uri);
        return photo && photo.mediaType === MediaLibrary.MediaType.video;
      });
    });
    _defineProperty(this, "checkSelection", item => {
      let videoSelected = this.isVideoSelected();
      let newSelected = [...this.state.selected];

      // Check video/photo selection
      if (item.mediaType === MediaLibrary.MediaType.video) {
        if (videoSelected && videoSelected !== item.uri) {
          // If different video is already selected, reset
          videoSelected = null;
          newSelected = [];
        } else if (!videoSelected && newSelected.length > 0) {
          // If photos selected, don't allow selecting video
          videoSelected = null;
          newSelected = [];
        }
        // Toggle video selected
        videoSelected = videoSelected !== item.uri ? item.uri : null;
      } else if (videoSelected) {
        // If video selected, reset
        videoSelected = null;
        newSelected = [];
      }

      // Check multiple selection
      const selectionLimit = this.props.max || defaultSelectionLimit;
      if (selectionLimit && selectionLimit > 1) {
        // Limit selection
        if (newSelected.length === selectionLimit && newSelected.indexOf(item.uri) === -1) return {
          isFull: true
        };
      } else {
        // Force single selection
        if (newSelected.length > 0 && newSelected[0] !== item.uri) newSelected = [];
      }
      return {
        newSelected,
        videoSelected
      };
    });
    _defineProperty(this, "selectImage", item => {
      const {
        newSelected,
        videoSelected,
        isFull
      } = this.checkSelection(item);
      if (isFull) return;
      if (newSelected.indexOf(item.uri) === -1) {
        newSelected.push(item.uri);
      } else {
        const deleteIndex = newSelected.indexOf(item.uri);
        newSelected.splice(deleteIndex, 1);
      }
      if (newSelected.length > this.props.max) return;
      if (!newSelected) newSelected = [];
      this.setState({
        selected: newSelected
      });
      this.props.onChange(newSelected, videoSelected, () => this.prepareCallback());
    });
    _defineProperty(this, "getPhotos", (reset = false) => {
      const {
        remoteAlbums,
        allowVideo,
        loadCount,
        album
      } = this.props;
      if (this.isLocal()) {
        // Retrieve local photos
        const mediaType = [MediaLibrary.MediaType.photo];
        if (allowVideo) mediaType.push(MediaLibrary.MediaType.video);
        const params = {
          first: loadCount || defaultLoadCount,
          mediaType,
          album: album || undefined,
          sortBy: [Platform.OS === "android" ? "modificationTime" : "creationTime"]
        };
        if (reset) {
          this.setState({
            photos: [],
            after: null,
            hasNextPage: true
          });
        } else {
          if (this.state.after) params.after = this.state.after;
          if (!this.state.hasNextPage) return;
        }
        MediaLibrary.getAssetsAsync(params).then(this.processPhotos);
      } else {
        var _selectedAlbum$images;
        // Use remote albums
        const selectedAlbum = remoteAlbums.find(item => item.id === album);
        if (selectedAlbum && ((_selectedAlbum$images = selectedAlbum.images) === null || _selectedAlbum$images === void 0 ? void 0 : _selectedAlbum$images.length) > 0) {
          const ordered = _.orderBy(selectedAlbum.images, "date", "desc");
          this.setState({
            photos: ordered.map(image => {
              return {
                uri: image.uri,
                mediaType: isVideo(image.uri) ? MediaLibrary.MediaType.video : MediaLibrary.MediaType.photo
              };
            }),
            isEmpty: false
          });
        } else {
          this.setState({
            photos: [],
            isEmpty: true
          });
        }
      }
    });
    _defineProperty(this, "processPhotos", data => {
      if (data.totalCount) {
        if (this.state.after === data.endCursor) return;
        const uris = data.assets;
        this.setState({
          photos: [...this.state.photos, ...uris],
          after: data.endCursor,
          hasNextPage: data.hasNextPage
        });
      } else {
        this.setState({
          isEmpty: true
        });
      }
    });
    _defineProperty(this, "getItemLayout", (data, index) => {
      const length = this.props.itemWidth || width / 4;
      return {
        length,
        offset: length * index,
        index
      };
    });
    _defineProperty(this, "renderImageTile", ({
      item,
      index
    }) => {
      if (!item) return null;
      const selectedIndex = this.state.selected.indexOf(item.uri);
      const selected = selectedIndex !== -1;
      return /*#__PURE__*/React.createElement(ImageTile, {
        selectedItemNumber: selectedIndex + 1,
        item: item,
        index: index,
        selected: selected,
        selectImage: this.selectImage,
        renderSelectedComponent: this.props.renderSelectedComponent,
        style: this.props.itemStyle,
        width: this.props.itemWidth,
        height: this.props.itemHeight,
        isRemote: !this.isLocal()
      });
    });
    _defineProperty(this, "renderPreloader", () => this.props.preloaderComponent || /*#__PURE__*/React.createElement(ActivityIndicator, {
      size: "large"
    }));
    _defineProperty(this, "renderEmptyState", () => this.props.emptyStateComponent || null);
    this.state = {
      hasCameraPermission: null,
      hasCameraRollPermission: null,
      numColumns: null,
      photos: [],
      selected: [],
      isEmpty: false,
      after: null,
      hasNextPage: true
    };
  }
  async componentDidMount() {
    if (this.isLocal()) await this.getPermissionsAsync();
    ScreenOrientation.addOrientationChangeListener(this.onOrientationChange);
    const orientation = await ScreenOrientation.getOrientationAsync();
    const numColumns = this.getNumColumns(orientation);
    this.setState({
      numColumns
    }, () => {
      this.getPhotos();
    });
  }
  componentDidUpdate(prevProps) {
    if (prevProps.album !== this.props.album) this.getPhotos(true);
    if (!_.isEqual(prevProps.selected, this.props.selected)) {
      this.setState({
        selected: this.props.selected
      });
    }
  }
  prepareCallback() {
    const {
      selected,
      photos
    } = this.state;
    const selectedPhotos = selected.map(uri => photos.find(p => p.uri === uri));
    if (this.isLocal()) {
      const assetsInfo = Promise.all(selectedPhotos.map(p => MediaLibrary.getAssetInfoAsync(p)));
      this.props.callback(assetsInfo);
    } else {
      // No need to retrieve local assets
      this.props.callback(selectedPhotos);
    }
  }
  renderImages() {
    if (_.isEmpty(this.state.photos) && !this.state.isEmpty) {
      return null;
    }
    return /*#__PURE__*/React.createElement(FlatList, {
      data: this.state.photos,
      numColumns: this.state.numColumns,
      key: this.state.numColumns,
      renderItem: this.renderImageTile,
      keyExtractor: (_, index) => index,
      onEndReached: () => {
        if (this.isLocal()) this.getPhotos();
      },
      onEndReachedThreshold: 0.5,
      ListEmptyComponent: this.state.isEmpty ? this.renderEmptyState() : this.renderPreloader(),
      initialNumToRender: 24,
      getItemLayout: this.getItemLayout
    });
  }
  render() {
    const {
      hasCameraPermission
    } = this.state;
    if (this.isLocal() && !hasCameraPermission) {
      return this.props.noCameraPermissionComponent || null;
    }
    return /*#__PURE__*/React.createElement(View, {
      style: [styles.container, this.props.style]
    }, this.renderImages());
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1
  }
});
//# sourceMappingURL=ImageBrowser.js.map