import { Component } from 'preact';

export class LongPress extends  Component<any, any> {
  private timer;
  private readonly longPressThreshold: number;

  constructor(props) {
    super(props);
    this.longPressThreshold = props.longPressThreshold || 200; // 默认0.2秒
  }

  handleStart = async (e) => {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
    e.preventDefault();
    this.timer = setTimeout(() => {
      this.props.onLongPress?.(e);
      this.timer = null;
    }, this.longPressThreshold);
  };

  handleEnd = async (e) => {
    // 清理计时器
    if (this.timer) {
      clearTimeout(this.timer);
      this.props.onClick?.(e);
      this.timer = null;
      return;
    }

    // 触发对应事件
    this.props.onRelease?.(e);
  };

  handleLeave = async () => {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  };

  componentWillUnmount() {
    if (this.timer) clearTimeout(this.timer);
  }

  render() {
    return (
      <div
        className={this.props.customClass}
        onMouseDown={this.handleStart}
        onMouseUp={this.handleEnd}
        onMouseLeave={this.handleLeave}
        onTouchStart={this.handleStart}
        onTouchEnd={this.handleEnd}
        onTouchCancel={this.handleEnd}
        onTouchMove={this.handleEnd}
        onClick={e => this.props.onRelease?.(e)}
      >
        {this.props.children}
      </div>
    );
  }
}

export default LongPress;
