import { dragEvent } from '../../utils'

interface Options {
  elWrapper: HTMLElement,
  elHandle: HTMLElement,
  dragHandle: any
}

export class DraggerFoundation {
  private elWrapper: HTMLElement
  private elHandle: HTMLElement
  private dragHandle: any
  private percent: number

  constructor(options: Options) {
    this.elWrapper = options.elWrapper
    this.elHandle = options.elHandle
    this.dragHandle = options.dragHandle
    this.percent = 0
    this.dragInit()
  }

  dragInit() {
    const dragConfig = {
      dragMove: (e: MouseEvent) => {
        this.dragMove(e)
      },
      dragStop: (e: MouseEvent) => {
        this.dragStop(e)
      }
    }
    dragEvent(this.elWrapper, dragConfig)
  }

  dragMove(e: MouseEvent) {
    const pleft = this.elWrapper.getBoundingClientRect().left
    const pwidth = this.elWrapper.getBoundingClientRect().width
    const percentData = e.clientX < pleft ? 0 : (e.clientX - pleft) / pwidth * 100
    this.percent = percentData > 100 ? 100 : percentData
    this.dragHandle(true, this.percent)
  }

  dragStop(e: MouseEvent) {
    this.dragHandle(false, this.percent)
  }
}