import state from "/src/state"
interface HorizontalDragScrollOptions {
   speed?: number // 滚动速度
   cursorGrab?: string // 抓取前的鼠标样式
}

class HorizontalDragScroll {
    private container: HTMLElement
    private options: HorizontalDragScrollOptions
    private isDown: boolean
    private startX: number
    private scrollLeft: number

    constructor(container: HTMLElement, options: HorizontalDragScrollOptions = {}) {
        this.container = container
        this.options = {
            speed: options.speed || 2,
            cursorGrab: options.cursorGrab || "grab",
        }

        this.isDown = false
        this.startX = 0
        this.scrollLeft = 0

        this.init()
    }

    private init() {
        this.container.style.cursor = this.options.cursorGrab || "grab"

        this.container.addEventListener("mousedown", this.onMouseDown.bind(this))
        this.container.addEventListener("mouseleave", this.onMouseLeave.bind(this))
        this.container.addEventListener("mouseup", this.onMouseUp.bind(this))
        this.container.addEventListener("mousemove", this.onMouseMove.bind(this))
    }

    private onMouseDown(e: MouseEvent) {
        // 当播放中或者不是一行谱模式  不起作用
        if(state.playState === "play" || !state.isSingleLine) {
            return
        }
        this.isDown = true
        this.startX = e.pageX - this.container.offsetLeft
        this.scrollLeft = this.container.scrollLeft
    }

    private onMouseLeave() {
        this.isDown = false
    }

    private onMouseUp() {
        this.isDown = false
    }

    private onMouseMove(e: MouseEvent) {
        if (!this.isDown) return
        e.preventDefault()
        const x = e.pageX - this.container.offsetLeft
        const walk = (x - this.startX) * (this.options.speed || 2)
        this.container.scrollLeft = this.scrollLeft - walk
    }

    public destroy() {
        this.container.removeEventListener("mousedown", this.onMouseDown.bind(this))
        this.container.removeEventListener("mouseleave", this.onMouseLeave.bind(this))
        this.container.removeEventListener("mouseup", this.onMouseUp.bind(this))
        this.container.removeEventListener("mousemove", this.onMouseMove.bind(this))
    }
    }

export default HorizontalDragScroll
