/* @jsx createElement */
import { Component, createElement } from 'rax';
import { isWeex, appInfo } from 'nuke-env';
import { connectStyle } from 'nuke-theme-provider';
import stylesProvider from '../styles';

class Switch extends Component {
  constructor(props) {
    super(props);

    this.handleClick = this.handleClick.bind(this);
    this.changeHandler = this.changeHandler.bind(this);
  }
  // shouldComponentUpdate(nextProps) {
  //   return (
  //     this.props.value !== nextProps.value ||
  //     this.props.disabled !== nextProps.disabled ||
  //     !styleEqual(this.props.themeStyle, nextProps.themeStyle)
  //   );
  // }
  handleClick(e) {
    if (this.props.disabled) {
      return null;
    }
    const newVal = !this.props.value;
    this.props.onValueChange && this.props.onValueChange.call(this, newVal);
  }
  changeHandler(e) {
    this.props.onValueChange && this.props.onValueChange(e.value);
  }
  render() {
    const { style, type, value, disabled, onValueChange, themeStyle, ...others } = this.props;
    let isIOS = appInfo.platform.toLowerCase() === 'ios';

    if (isWeex) {
      const nativeProps = {
        style: Object.assign({}, isIOS ? {} : { width: 95, height: 60 }, style),
        checked: value,
        disabled,
      };

      return <switch {...others} {...nativeProps} onChange={this.changeHandler} />;
    }

    const styles = themeStyle;

    if (type) {
      isIOS = type === 'iOS';
    }
    let wrapStyle = Object.assign(
      {},
      styles.wrap,
      value ? styles.checkedWrap : styles.uncheckedWrap,
      disabled ? styles.disabledWrap : {},
      disabled ? styles[`disabled${value ? 'Checked' : 'UnChecked'}Wrap`] : {},
      style
    );
    if (isIOS) {
      wrapStyle = Object.assign(
        {},
        styles.wrapIOS,
        value ? styles.checkedWrapIOS : styles.uncheckedWrapIOS,
        disabled ? styles.disabledWrapIOS : {},
        disabled ? styles[`disabled${value ? 'Checked' : 'UnChecked'}WrapIOS`] : {},
        style
      );
    }
    let dotStyle = Object.assign(
      {},
      styles.dot,
      value ? styles.checkedDot : styles.uncheckedDot,
      disabled ? styles.disabledDot : {}
    );
    if (isIOS) {
      dotStyle = Object.assign(
        {},
        styles.dotIOS,
        value ? styles.checkedDotIOS : styles.uncheckedDotIOS,
        disabled ? styles.disabledDotIOS : {}
      );
    }
    return (
      <span onClick={this.handleClick} style={wrapStyle} {...others}>
        <small style={dotStyle} />
      </span>
    );
  }
}
Switch.displayName = 'Switch';
Switch.defaultProps = {
  disabled: false,
  style: {},
  type: null,
};
export default connectStyle(stylesProvider)(Switch);
