import create from './dom/create'
import insertBefore from './dom/insertBefore'

export default class RadialProgressBar {
  private _circumference: number
  private _element: SVGElement
  private _value = 0

  static onFindFunction(size: number, stroke: number) {
    return (progressBar: HTMLDivElement) => {
      const rpb = new RadialProgressBar(
        size,
        stroke,
        parseInt(progressBar.style.getPropertyValue('--progress')),
      )
      insertBefore(rpb.getElement(), progressBar)
      progressBar.hidden = true
    }
  }

  constructor(size: number, stroke: number, initialValue = 0) {
    const container = create('div')
    const center = size / 2
    const radius = center - stroke / 2
    this._circumference = 2 * Math.PI * radius

    container.innerHTML = `
      <svg class="RPB" viewBox="0 0 ${size} ${size}">
        <circle
          class="RPB-bg"
          cx="${center}"
          cy="${center}"
          r="${radius}"
          stroke-width="${stroke - 1}"
        />
        <circle
          class="RPB-fg"
          cx="${center}"
          cy="${center}"
          r="${radius}"
          stroke-width="${stroke}"
          stroke-dasharray="${this._circumference}"
          stroke-dashoffset="${this._circumference}"
        />
      </svg>
    `

    if (!(container.firstElementChild instanceof SVGElement))
      throw new Error('SVG not found')

    this._element = container.firstElementChild
    this.setValue(initialValue)
  }

  getElement() {
    return this._element
  }

  getValue() {
    return this._value
  }

  setValue(value: number) {
    this._value = value

    this._element
      .querySelector<HTMLElement>(':scope > .RPB-fg')
      ?.setAttribute(
        'stroke-dashoffset',
        `${this._circumference * (1 - value / 100)}`,
      )
  }
}
