import { fabric } from 'fabric'

export class QLine extends fabric.Group {
  line
  text
  fontSize
  length = 0
  x1
  y1
  x2
  y2
  direction
  type = 'HelpLine'
  parent
  #lengthTxt = 0

  constructor(points, option, lengthTxt) {
    const [x1, y1, x2, y2] = points

    if (!option.fontSize) {
      throw new Error('Font size is required.')
    }

    const line = new fabric.Line(points, { ...option, strokeWidth: 1 })
    super([line], {})

    this.x1 = x1
    this.y1 = y1
    this.x2 = x2
    this.y2 = y2
    this.line = line
    this.fontSize = option.fontSize
    this.direction = option.direction
    this.parent = option.parent

    if (lengthTxt > 0) {
      this.#lengthTxt = Number(lengthTxt)
    }

    this.#init()
    this.#addControl()
  }

  #init() {
    this.#addLengthText(true)
  }

  #addControl() {
    this.on('moving', () => {
      this.#addLengthText(false)
    })

    this.on('modified', (e) => {
      this.#addLengthText(false)
    })

    this.on('selected', () => {
      Object.keys(this.controls).forEach((controlKey) => {
        if (controlKey !== 'ml' && controlKey !== 'mr') {
          this.setControlVisible(controlKey, false)
        }
      })
    })
  }

  #addLengthText(isFirst) {
    if (this.text) {
      this.removeWithUpdate(this.text)
      this.text = null
    }

    if (isFirst && this.#lengthTxt > 0) {
      const text = new fabric.Textbox(this.#lengthTxt.toFixed(0).toString(), {
        left: (this.x1 + this.x2) / 2,
        top: (this.y1 + this.y2) / 2,
        fontSize: this.fontSize,
      })
      this.length = this.#lengthTxt
      this.text = text
      this.addWithUpdate(text)
      return
    }

    const scaleX = this.scaleX
    const scaleY = this.scaleY
    const x1 = this.left
    const y1 = this.top
    const x2 = this.left + this.width * scaleX
    const y2 = this.top + this.height * scaleY
    const dx = x2 - x1
    const dy = y2 - y1
    this.length = Number(Math.sqrt(dx * dx + dy * dy).toFixed(0))

    const text = new fabric.Textbox(this.length.toFixed(0).toString(), {
      left: (x1 + x2) / 2,
      top: (y1 + y2) / 2,
      fontSize: this.fontSize,
    })
    this.text = text
    this.addWithUpdate(text)
  }

  setFontSize(fontSize) {
    this.fontSize = fontSize
    this.text.set({ fontSize })
    this.addWithUpdate()
  }
}
