import * as React from 'react';
import styles from './index.less';
import { RendererProps } from '../../..';

abstract class BasePickableRenderer<T> extends React.Component<RendererProps<T>> {
  ref = React.createRef<HTMLDivElement>();

  abstract pickable(): boolean;

  abstract openPicker(): void;

  constructor(props: RendererProps<T>) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.openPicker = this.openPicker.bind(this);
  }

  // #region 阻止单元格再次点击后进入 active 状态
  handleClick(e: MouseEvent) {
    const { isCellSelected } = this.props;
    const isSelected = isCellSelected!(this.props.id);

    // 这里如果不正确, 多半是因为 valor-hooks 的包存在多份引用
    if (isSelected) {
      e.stopPropagation();
    }

    this.openPicker();
  }

  componentDidMount() {
    if (this.pickable()) {
      this.ref.current && this.ref.current.addEventListener('mousedown', this.handleClick, false);
    }
  }

  componentWillUnmount() {
    if (this.pickable()) {
      this.ref.current &&
        this.ref.current.removeEventListener('mousedown', this.handleClick, false);
    }
  }

  getTrigger(align: 'left' | 'right' = 'right') {
    var style: React.CSSProperties =
      align === 'left' ? { textAlign: 'left', left: 0 } : { textAlign: 'right', right: 0 };

    return (
      <div className={styles['open-picker']} ref={this.ref} style={style}>
        ...
      </div>
    );
  }
}

export default BasePickableRenderer;
