/** @jsx createElement */
import { createElement, Component, PropTypes } from 'rax';
import View from 'nuke-view';
import Text from 'nuke-text';
import { isWeex } from 'nuke-env';
import { connectStyle } from 'nuke-theme-provider';

import Icon from 'nuke-icon';
import stylesProvider from '../styles';

class Toast extends Component {
  constructor() {
    super();
    this.timer = null;
    this.state = {
      visible: true,
    };
    this.displayName = 'Toast';
  }

  componentDidMount() {}

  shouldComponentUpdate() {
    if (isWeex) {
      return true;
    }
    return false;
  }
  getIcon() {
    const { message, icon, others } = this.props;
    const styles = this.props.themeStyle;
    if (!icon) return;
    if (icon.name) {
      return <Icon size="large" style={[styles.iconfont, icon.style]} name={icon.name} />;
    }
    return <Icon style={icon.style} src={icon.source} />;
  }
  // 启动这计时器
  startTimer() {
    const that = this;

    // 先清掉计时器
    clearTimeout(that.timer);

    const duration = that.props.duration;
    if (duration <= 0) return;

    that.timer = setTimeout(() => {
      that.setState({ visible: false });
      that.props.onClose && that.props.onClose();
    }, duration);
  }
  render() {
    this.startTimer();
    const { message, icon, others } = this.props;
    const styles = this.props.themeStyle;
    const bodyStyle = Object.assign({}, styles.body, icon ? styles['body-with-icon'] : {});
    // console.log(bodyStyle);
    return this.state.visible ? (
      <View style={styles.mask} {...others}>
        <View style={bodyStyle}>
          {this.getIcon()}
          <Text style={[styles.text, icon ? styles['text-with-icon'] : {}]}>{message}</Text>
        </View>
      </View>
    ) : null;
  }
}
Toast.propTypes = {
  // 持续时间, 如果<=0表示一直存在
  duration: PropTypes.number,
  // 是否显示
  visible: PropTypes.bool,
  defaultVisible: PropTypes.bool,
  onClose: PropTypes.func,
};

Toast.defaultProps = {
  duration: 0,
  hasMask: false,
};
const StyledToast = connectStyle(stylesProvider)(Toast);

export default StyledToast;
