/** @jsx createElement */

'use strict';

import { createElement, Component, findDOMNode, PropTypes } from 'rax';
import { Detection } from 'nuke-ep-utils';
import { connectStyle } from 'nuke-theme-provider';
import Emitter from '../util/emitter';
import stylesProvider from '../styles/index';
import View from 'nuke-view';
// 在weex及非android4.4以下的机器中才使用ep绑定
let expressionBinding = {};
try {
  expressionBinding = require('@weex-module/expressionBinding');
} catch (e) { }
class Item extends Component {
  constructor(props) {
    super(props);
    this.isPaning = false;
    this.isAppear = false;
  }

  componentDidMount() {
    setTimeout(() => {
      if (Detection.epEnable && Detection.Android) {
        try {
          const element = findDOMNode(this);
          if (element && element.ref) {
            expressionBinding.enableBinding(element.ref, 'pan');
          }
        } catch (e) {
          console.error('pancell findDOMNode error');
        }
      }
    }, 300);
  }

  // use for andorid
  // @todo  事件绑定存在问题，当list作为子元素时无法触发横向滚动
  //  @todo bug  android事件冒泡需要在list的cell中再次绑定onHorizontalPan，作为事件anchor
  onHorizontalPan = (e) => {
    if (e.state === 'start') {
      this.isPanning = true;
      Emitter.emit('slider', {
        element: findDOMNode(this),
      });
    } else if (e.state === 'end') {
      setTimeout(() => {
        this.isPanning = false;
      }, 50);
    }
  };

  onItemAppear = (e) => {
    if (Detection.epEnable && Detection.Android) {
      const element = findDOMNode(this);
      if (element && element.ref) {
        expressionBinding.enableBinding(element.ref, 'pan');
      }
    }
    const { onAppear, exposure } = this.props;

    if (exposure === true && !this.isAppear) {
      this.isAppear = true;
    }

    if (typeof onAppear === 'function') {
      onAppear(e);
    }
  };

  onItemDisAppear = (e) => {
    if (Detection.epEnable && Detection.Android) {
      const element = findDOMNode(this);
      if (element && element.ref) {
        expressionBinding.disableBinding(element.ref, 'pan');
      }
    }

    const { onDisAppear } = this.props;
    if (typeof onDisAppear === 'function') {
      onDisAppear(e);
    }
  };
  onClick = (e) => {
    // console.log('click-->', e);
  };
  render() {
    const { style, children, themeStyle } = this.props;
    return (
      <View
        {...this.props}
        style={[themeStyle.container, style]}
        preventMoveEvent={false}
        onAppear={this.onItemAppear}
        onClick={this.onClick}
        onDisAppear={this.onItemDisAppear}
        onHorizontalPan={this.onHorizontalPan}
      />
    );
  }
}

// Item.propTypes = {};

// Item.defaultProps = {};
Item.displayName = 'Ep-Tabbar';

export default connectStyle(stylesProvider)(Item);
