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

import { ifIphoneX } from 'react-native-iphone-x-helper';

import { stylePropType } from './propTypes';

import Constants from './constants';
import { Photo } from './media';

// 1 margin and 1 border width
const ITEM_MARGIN = 2;

export default class GridContainer extends React.Component {

  static propTypes = {
    style: stylePropType,
    mediaList: PropTypes.array.isRequired,
    square: PropTypes.bool,
    displaySelectionButtons: PropTypes.bool,
    onPhotoTap: PropTypes.func,
    itemPerRow: PropTypes.number,

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

    /**
     * offsets the width of the grid
     */
    offset: PropTypes.number,
  };

  static defaultProps = {
    displaySelectionButtons: false,
    onPhotoTap: () => {},
    itemPerRow: 3,
  };

  constructor(props) {
    super(props);
    // 列宽由窗口宽度算出。放进 state(而不是在 renderItem 里直接读 Dimensions)
    // 才能让转屏生效:本容器从不卸载 —— FullScreenContainer 靠动画 marginTop
    // 把它移出屏幕来隐藏,所以没有订阅就永远停在首次渲染时的宽度。
    this.state = { windowWidth: Dimensions.get('window').width };

    // 按 index 缓存回调闭包,避免每次 render 都为 onPress/onSelection 创建
    // 新的函数引用,减少长列表滚动时的子树 diff 成本(做法与
    // FullScreenContainer 的 _photoRefSetter 一致)。
    this._onPhotoTapHandlers = new Map();
    this._onMediaSelectionHandlers = new Map();
  }

  _getOnPhotoTapHandler(index) {
    let handler = this._onPhotoTapHandlers.get(index);
    if (!handler) {
      handler = () => this.props.onPhotoTap(index);
      this._onPhotoTapHandlers.set(index, handler);
    }
    return handler;
  }

  _getOnMediaSelectionHandler(index) {
    let handler = this._onMediaSelectionHandlers.get(index);
    if (!handler) {
      handler = (isSelected) => this.props.onMediaSelection(this.props.mediaList[index], index, isSelected);
      this._onMediaSelectionHandlers.set(index, handler);
    }
    return handler;
  }

  componentDidMount() {
    this._dimensionsSubscription = Dimensions.addEventListener('change', ({ window }) => {
      if (window && window.width !== this.state.windowWidth) {
        this.setState({ windowWidth: window.width });
      }
    });
  }

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

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

  renderItem = ({ item, index }) => {
    const {
      displaySelectionButtons,
      itemPerRow,
      square,
      offset,
    } = this.props;
    const screenWidth = this.state.windowWidth - offset;
    const photoWidth = (screenWidth / itemPerRow) - (ITEM_MARGIN * 2);

    return (
      <TouchableHighlight onPress={this._getOnPhotoTapHandler(index)}>
        <View style={styles.row}>
          <Photo
            width={photoWidth}
            height={square ? photoWidth : 100}
            resizeMode={'cover'}
            thumbnail
            progressImage={require('../Assets/hourglass.png')}
            displaySelectionButtons={displaySelectionButtons}
            uri={item.thumb || item.photo}
            selected={item.selected}
            onSelection={this._getOnMediaSelectionHandler(index)}
          />
        </View>
      </TouchableHighlight>
    );
  }

  // 九宫格每格高度可由 photoWidth/square 推导为固定值,补 getItemLayout 避免
  // FlatList 布局测量抖动;计算方式需与 renderItem 中的 photoWidth 保持一致。
  getItemLayout = (data, index) => {
    const { itemPerRow, square, offset } = this.props;
    const { windowWidth } = this.state;
    const screenWidth = windowWidth - offset;
    const photoWidth = (screenWidth / itemPerRow) - (ITEM_MARGIN * 2);
    const itemHeight = (square ? photoWidth : 100) + (ITEM_MARGIN * 2);
    const row = Math.floor(index / itemPerRow);

    return { length: itemHeight, offset: itemHeight * row, index };
  }

  render() {
    const { mediaList, itemPerRow } = this.props;
    const { windowWidth } = this.state;

    return (
      <View style={styles.container}>
        <FlatList
          // FlatList 不支持运行时改 numColumns,key 变了才会整表重建。
          // 宽度并入 key 同理:转屏后需整表重建列宽才会重算,否则 FlatList 会
          // 沿用已缓存的 cell,宽度停在上一个方向算出的值(U-10)。
          key={`grid_${itemPerRow}_${windowWidth}`}
          keyExtractor={this.keyExtractor}
          data={mediaList}
          initialNumToRender={21}
          // 上游写死 3:itemPerRow 只参与 photoWidth 计算,列数不跟着变,
          // 于是 itemPerRow=4 只把缩略图改窄、每行仍是 3 张,与它自己的文档
          // (README「Sets images amount in grid row」)矛盾。判我方更优予以修复。
          numColumns={itemPerRow}
          renderItem={this.renderItem}
          getItemLayout={this.getItemLayout}
          // 收窄同时驻留的行数以降低长图集的内存占用(DFX C2)。
          windowSize={10}
          // deliberate: this list stays mounted while the full screen view is
          // on top of it (it is only pushed off screen by an animated
          // marginTop), and clipping its subviews there makes the thumbnails
          // come back blank when the grid slides in again.
          removeClippedSubviews={false}
        />
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: ifIphoneX(18, 0),
    paddingBottom: Constants.TOOLBAR_HEIGHT,
  },
  row: {
    justifyContent: 'center',
    margin: 1,
    alignItems: 'center',
    borderWidth: 1,
    borderRadius: 1,
  },
});