/** @jsx createElement */
import { createElement, Component, PropTypes } from 'rax';
import { View, Env, Image, Mask, ThemeProvider } from 'weex-nuke';
import stylesProvider from './styles';

const { connectStyle } = ThemeProvider;

const { isWeb } = Env;

class CustomLoading extends Component {
  constructor(props) {
    super(props);
    const defaultVisible = props.defaultVisible;
    this.state = {
      shown: defaultVisible,
    };
    this.show = this.show.bind(this);
    this.hide = this.hide.bind(this);
    this.onShow = this.onShow.bind(this);
    this.onHide = this.onHide.bind(this);
  }

  componentDidMount() {
    this.loading = this.refs.mask;
    if (this.state.shown) {
      this.show();
    }
  }
  shouldComponentUpdate(nextProps, nextState) {
    return nextState.shown !== this.state.shown;
  }
  onShow() {
    this.props.onShow && this.props.onShow();
  }
  onHide() {
    this.setState({
      shown: false,
    });
    this.props.onHide && this.props.onHide();
  }

  show() {
    if (this.loading) {
      this.setState({
        shown: true,
      });
      this.loading.show && this.loading.show();
    }
  }
  hide() {
    if (this.loading) {
      this.loading.hide && this.loading.hide();
    }
  }
  wrapPress(e) {
    if (isWeb) {
      e.stopPropagation();
    }
  }
  touchMove(e) {
    if (isWeb) {
      e.preventDefault();
    }
  }

  render() {
    const styles = this.props.themeStyle;
    const { image = { style: {} }, animate, style = {} } = this.props;

    const imageWrap = Object.assign(
      {},
      styles.imageWrap,
      image.style.width ? { width: image.style.width } : {},
      image.style.height ? { height: image.style.height } : {}
    );
    return (
      <Mask
        style={[styles.mask, style]}
        maskClosable={false}
        defaultVisible={false}
        animate={animate}
        onShow={this.onShow}
        onHide={this.onHide}
        onTouchmove={this.touchMove}
        ref="mask"
      >
        <View style={imageWrap}>
          <Image
            source={{ uri: image.uri }}
            style={[styles.image, image.style]}
            resizeMode={'cover'}
            quality={'original'}
          />
        </View>
      </Mask>
    );
  }
}
CustomLoading.propTypes = {
  themeStyle: PropTypes.any,
  style: PropTypes.any,
  image: PropTypes.any,
  onHide: PropTypes.func,
  onShow: PropTypes.func,
};

CustomLoading.defaultProps = {
  themeStyle: {},
  image: {},
  style: {},
  animate: true,
  onHide: () => { },
  onShow: () => { },
};
CustomLoading.displayName = 'CustomLoading';
const StyledCustomLoading = connectStyle(stylesProvider)(CustomLoading);

export default StyledCustomLoading;
