import { fabric } from 'fabric'
export default class QRect extends fabric.Rect {
  #text = []
  #viewLengthText
  #fontSize
  type = 'QRect'
  constructor(option) {
    if (!option.fontSize) {
      throw new Error('Font size is required.')
    }
    super(option)
    this.#fontSize = option.fontSize
    this.#init(option)
    this.#addControl()
  }

  #init(option) {
    this.#viewLengthText = option.viewLengthText ?? true
  }

  setViewLengthText(bool) {
    this.#viewLengthText = bool
    this.#addLengthText()
  }

  setFontSize(fontSize) {
    this.#fontSize = fontSize
    this.#addLengthText()
  }

  #addControl() {
    this.on('removed', () => {
      if (this.#text.length > 0) {
        this.#text.forEach((text) => {
          this.canvas.remove(text)
        })
        this.#text = []
      }
    })

    this.on('added', () => {
      this.#addLengthText()
    })

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

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

    this.on('moving', () => {
      this.#addLengthText()
    })
  }
  #addLengthText() {
    if (this.#text.length > 0) {
      this.#text.forEach((text) => {
        this.canvas.remove(text)
      })
      this.#text = []
    }

    if (!this.#viewLengthText) {
      return
    }

    const scaleX = this.scaleX
    const scaleY = this.scaleY

    const lines = [
      {
        start: { x: this.left, y: this.top },
        end: { x: this.left + this.width * scaleX, y: this.top },
      },
      {
        start: { x: this.left, y: this.top + this.height * scaleY },
        end: { x: this.left, y: this.top },
      },
    ]

    lines.forEach((line) => {
      const dx = line.end.x - line.start.x
      const dy = line.end.y - line.start.y
      const length = Math.sqrt(dx * dx + dy * dy)

      const text = new fabric.Text(length.toFixed(0), {
        left: (line.start.x + line.end.x) / 2,
        top: (line.start.y + line.end.y) / 2,
        fontSize: this.#fontSize,
        selectable: false,
      })
      this.#text.push(text)
      this.canvas.add(text)
    })
  }
}
