import React from 'react';
import PropTypes from 'prop-types';
import {
  DeviceEventEmitter,
  Dimensions,
  FlatList,
  View,
  StyleSheet,
  StatusBar,
  TouchableWithoutFeedback
} from 'react-native';

import { stylePropType } from './propTypes';
import Constants from './constants';
import { BottomBar } from './bar';
import { Photo } from './media';

export default class FullScreenContainer extends React.Component {

  static propTypes = {
    style: stylePropType,
    mediaList: PropTypes.array.isRequired,
    /*
     * opens grid view
     */
    onGridButtonTap: PropTypes.func,

    /*
     * Display top bar
     */
    displayTopBar: PropTypes.bool,

    /*
     * updates top bar title
     */
    updateTitle: PropTypes.func,

    /*
     * displays/hides top bar
     */
    toggleTopBar: PropTypes.func,

    /*
     * refresh the list to apply selection change
     */
    onMediaSelection: PropTypes.func,

    /*
     * those props are inherited from main PhotoBrowser component
     * i.e. index.js
     */
    initialIndex: PropTypes.number,
    alwaysShowControls: PropTypes.bool,
    displayActionButton: PropTypes.bool,
    displayNavArrows: PropTypes.bool,
    alwaysDisplayStatusBar: PropTypes.bool,
    displaySelectionButtons: PropTypes.bool,
    enableGrid: PropTypes.bool,
    useCircleProgress: PropTypes.bool,
    onActionButton: PropTypes.func,
    onPhotoLongPress: PropTypes.func,
    delayLongPress: PropTypes.number,

    /**
     * Use a custom button in the bottom bar to the left of the Share button,
     * without having to recreate the entire bottom bar and pass it in with the
     * `bottomBarComponent` prop. The visibility of the Share button can still
     * be controlled with `displayActionButton`.
     */
    customBottomBarButton: PropTypes.element,
  };

  static defaultProps = {
    initialIndex: 0,
    displayTopBar: true,
    displayNavArrows: false,
    alwaysDisplayStatusBar: false,
    displaySelectionButtons: false,
    enableGrid: true,
    onGridButtonTap: () => {},
    onPhotoLongPress: () => {},
    delayLongPress: 1000,
  };

  constructor(props, context) {
    super(props, context);

    this._renderItem = this._renderItem.bind(this);
    this._toggleControls = this._toggleControls.bind(this);
    this._onScroll = this._onScroll.bind(this);
    this._onNextButtonTapped = this._onNextButtonTapped.bind(this);
    this._onPhotoLongPress = this._onPhotoLongPress.bind(this);
    this._onPreviousButtonTapped = this._onPreviousButtonTapped.bind(this);
    this._onActionButtonTapped = this._onActionButtonTapped.bind(this);

    this.photoRefs = [];
    // one retry chain per photo index; a single handle would only let
    // componentWillUnmount cancel the most recent chain (see _triggerPhotoLoad)
    this._photoLoadTimers = new Map();
    this._photoRefSetters = new Map();
    // 按 index 缓存 onSelection 闭包,避免每次 render 都创建新函数引用
    // (做法与 _photoRefSetter 一致),减少长列表滚动时的子树 diff 成本。
    this._onSelectionSetters = new Map();
    this._isUnmounted = false;

    // clamp here as well as in openPage(): render reads currentMedia.caption,
    // and it runs before componentDidMount gets a chance to clamp, so an
    // out-of-range initialIndex from the host would crash on the first frame.
    const initialIndex = this._clampIndex(props.initialIndex, props.mediaList);

    this.state = {
      currentIndex: initialIndex,
      currentMedia: props.mediaList[initialIndex],
      controlsDisplayed: props.displayTopBar,
      viewportWidth: Dimensions.get('window').width,
      viewportHeight: Dimensions.get('window').height,
    };
  }

  _clampIndex(index, mediaList = this.props.mediaList) {
    if (!mediaList.length) {
      return 0;
    }
    return Math.max(0, Math.min(index, mediaList.length - 1));
  }

  componentDidMount() {
    // Upstream never removes this listener; the callback keeps photoRefs alive
    // and forceUpdate()s unmounted photos once the browser is opened a second
    // time. Store the subscription and drop it on unmount, same as
    // GridContainer does for its Dimensions subscription.
    this._dimensionsSubscription = DeviceEventEmitter.addListener('didUpdateDimensions', () => {
      this.photoRefs.map(p => p && p.forceUpdate());
      this.openPage(this.state.currentIndex, false);
    });

    this.openPage(this.state.currentIndex, false);
  }

  componentWillUnmount() {
    this._isUnmounted = true;

    if (this._dimensionsSubscription) {
      this._dimensionsSubscription.remove();
      this._dimensionsSubscription = null;
    }

    this._photoLoadTimers.forEach(timerId => clearTimeout(timerId));
    this._photoLoadTimers.clear();
  }

  openPage(index, animated) {
    const { mediaList } = this.props;

    if (!this.flatListView || !mediaList.length) {
      return;
    }

    // scrollToIndex throws an Invariant Violation (red screen) for an
    // out-of-range index, which a host can trigger through initialIndex.
    const safeIndex = this._clampIndex(index, mediaList);

    this.flatListView.scrollToIndex({
      index: safeIndex,
      animated,
    });

    this._updatePageIndex(safeIndex);
  }

  _updatePageIndex(index) {
    this.setState({
      currentIndex: index,
      currentMedia: this.props.mediaList[index],
    }, () => {
      this._triggerPhotoLoad(index);

      const { customTitle, mediaList } = this.props;

      const rowCount = mediaList.length;
      const newTitle = customTitle ? customTitle(index + 1, rowCount) : `${index + 1} of ${rowCount}`;
      this.props.updateTitle(newTitle);
    });
  }

  _triggerPhotoLoad(index) {
    if (this._isUnmounted) {
      return;
    }

    // drop any chain already pending for this index, otherwise repeatedly
    // paging back and forth spawns duplicated retry chains that keep firing
    // redundant load() calls.
    const pendingTimerId = this._photoLoadTimers.get(index);
    if (pendingTimerId) {
      clearTimeout(pendingTimerId);
      this._photoLoadTimers.delete(index);
    }

    const photo = this.photoRefs[index];
    if (photo) {
      photo.load();
      return;
    }

    // HACK: photo might be undefined when user taps a photo from gridview
    // that hasn't been rendered yet.
    // photo is rendered after listView's scrollTo method call
    // and i'm deferring photo load method for that.
    // Every retry chain is tracked by its own index so componentWillUnmount can
    // cancel all of them: after unmount React nulls out photoRefs, so a chain
    // left running would re-arm itself every interval forever while holding on
    // to this container.
    const timerId = setTimeout(() => this._triggerPhotoLoad(index), Constants.PHOTO_LOAD_RETRY_INTERVAL);
    this._photoLoadTimers.set(index, timerId);
  }

  _toggleControls() {
    const { alwaysShowControls, toggleTopBar } = this.props;

    if (!alwaysShowControls) {
      const controlsDisplayed = !this.state.controlsDisplayed;
      this.setState({
        controlsDisplayed,
      });
      toggleTopBar(controlsDisplayed);
    }
  }

  _onNextButtonTapped() {
    let nextIndex = this.state.currentIndex + 1;
    // go back to the first item when there is no more next item
    if (nextIndex > this.props.mediaList.length - 1) {
      nextIndex = 0;
    }
    this.openPage(nextIndex, false);
  }

  _onPreviousButtonTapped() {
    let prevIndex = this.state.currentIndex - 1;
    // go to the last item when there is no more previous item
    if (prevIndex < 0) {
      prevIndex = this.props.mediaList.length - 1;
    }
    this.openPage(prevIndex, false);
  }

  _onActionButtonTapped() {
    const onActionButton = this.props.onActionButton;

    // action behaviour must be implemented by the client
    // so, call the client method or simply ignore this event
    if (onActionButton) {
      const { currentMedia, currentIndex } = this.state;
      onActionButton(currentMedia, currentIndex);
    }
  }

  _onScroll(e) {
    const event = e.nativeEvent;
    const layoutWidth = event.layoutMeasurement.width || Dimensions.get('window').width;
    const newIndex = Math.floor((event.contentOffset.x + 0.5 * layoutWidth) / layoutWidth);

    this._onPageSelected(newIndex);
  }

  _onPageSelected(page) {
    const { currentIndex } = this.state;
    const newIndex = this._clampIndex(page);

    if (currentIndex !== newIndex) {
      this._updatePageIndex(newIndex);

      if (this.state.controlsDisplayed && !this.props.displayTopBar) {
        this._toggleControls();
      }
    }
  }

  _onPhotoLongPress() {
    const onPhotoLongPress = this.props.onPhotoLongPress;
    const { currentMedia, currentIndex } = this.state;
    onPhotoLongPress(currentMedia, currentIndex);
  }

  // a fresh arrow function on every render would make React detach (ref(null))
  // and re-attach the ref each time, so _triggerPhotoLoad can observe a null
  // photo and needlessly wait another retry interval. Cache one setter per
  // index instead.
  _photoRefSetter(index) {
    let setter = this._photoRefSetters.get(index);
    if (!setter) {
      setter = ref => { this.photoRefs[index] = ref; };
      this._photoRefSetters.set(index, setter);
    }
    return setter;
  }

  _getOnSelectionSetter(index) {
    let setter = this._onSelectionSetters.get(index);
    if (!setter) {
      setter = isSelected => this.props.onMediaSelection(this.props.mediaList[index], index, isSelected);
      this._onSelectionSetters.set(index, setter);
    }
    return setter;
  }

  _renderItem({ item, index }) {
    const {
      displaySelectionButtons,
      useCircleProgress,
    } = this.props;

    return (
      <View style={{ width: this.state.viewportWidth, height: this.state.viewportHeight }}>
        <TouchableWithoutFeedback
          onPress={this._toggleControls}
          onLongPress={this._onPhotoLongPress}
          delayLongPress={this.props.delayLongPress}>
          <Photo
            ref={this._photoRefSetter(index)}
            lazyLoad
            useCircleProgress={useCircleProgress}
            uri={item.photo}
            width={this.state.viewportWidth}
            height={this.state.viewportHeight}
            displaySelectionButtons={displaySelectionButtons}
            selected={item.selected}
            onSelection={this._getOnSelectionSetter(index)}
          />
        </TouchableWithoutFeedback>
      </View>
    );
  }

  getItemLayout = (data, index) => (
    { length: this.state.viewportWidth, offset: this.state.viewportWidth * index, index }
  )

  _onLayout = ({ nativeEvent: { layout } }) => {
    if (layout.width > 0 && layout.height > 0 &&
        (layout.width !== this.state.viewportWidth || layout.height !== this.state.viewportHeight)) {
      this.setState({ viewportWidth: layout.width, viewportHeight: layout.height },
        () => this.openPage(this.state.currentIndex, false));
    }
  }

  _renderScrollableContent() {
    const { mediaList } = this.props;

    return (
      <FlatList
        ref={flatListView => this.flatListView = flatListView}
        data={mediaList}
        // Grid transitions and safe-area layout change the viewport while
        // data/renderItem stay the same. FlatList is a PureComponent: without
        // extraData, the first mounted photo keeps its previous size/position.
        extraData={this.state}
        renderItem={this._renderItem}
        onScroll={this._onScroll}
        onLayout={this._onLayout}
        keyExtractor={this._keyExtractor}
        horizontal
        pagingEnabled
        bounces={false}
        overScrollMode="never"
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}
        directionalLockEnabled
        scrollEventThrottle={16}
        getItemLayout={this.getItemLayout}
        initialScrollIndex={this.state.currentIndex}
        // 收窄同时驻留的大图数量以降低内存占用(DFX C2)。
        // removeClippedSubviews 需先实测懒加载图片是否被裁剪回收后再决定是否开启,
        // 此处不开启,避免改变现有懒加载行为。
        windowSize={5}
      />
    );
  }

  _keyExtractor = item => item.id || item.thumb || item.photo;

  render() {
    const {
      displayNavArrows,
      alwaysDisplayStatusBar,
      displayActionButton,
      onGridButtonTap,
      enableGrid,
      customBottomBarButton,
    } = this.props;
    const { controlsDisplayed, currentMedia } = this.state;
    const BottomBarComponent = this.props.bottomBarComponent || BottomBar;

    return (
      <View style={styles.flex}>
        <StatusBar
          hidden={alwaysDisplayStatusBar ? false : !controlsDisplayed}
          showHideTransition={'slide'}
          barStyle={'light-content'}
          animated
          translucent
        />
        {this._renderScrollableContent()}
        <BottomBarComponent
          displayed={controlsDisplayed}
          height={Constants.TOOLBAR_HEIGHT}
          displayNavArrows={displayNavArrows}
          displayGridButton={enableGrid}
          displayActionButton={displayActionButton}
          caption={currentMedia.caption}
          media={currentMedia}
          onPrev={this._onPreviousButtonTapped}
          onNext={this._onNextButtonTapped}
          onGrid={onGridButtonTap}
          onAction={this._onActionButtonTapped}
          customButton={customBottomBarButton}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  flex: {
    flex: 1,
  },
});