import { Drag } from './drag'
import { Node } from './node'
import { NodeList } from './nodelist'

const nodeSize = 30

export class NodeView {
  node: Node
  el: HTMLElement
  size = 1
  private _startPosition: number[] = []
  private _drag: Drag
  selected = false

  constructor(node: Node, nodeList: NodeList, private onClick = (_nodeView: NodeView, _nodeList: NodeList, _e: MouseEvent): void => {}) {
    this.node = node
    this.el = document.createElement('div')
    this.el.className = `pin-${node.id} pin`
    this.el.style.position = 'absolute'
    this.el.innerHTML = node.label ? `${node.label}` : `${node.id}`

    this.el.addEventListener('click', (e: MouseEvent) => {
      this.onClick(this, nodeList, e)
    })

    this._drag = new Drag(this.el, this.onDrag.bind(this), this.onStart.bind(this))

    this.update()
  }

  onStart() {
    this._startPosition = [...this.node.position]
  }

  translate(x: number, y: number) {
    const node = this.node
    const params = { node, x, y }

    node.position[0] = params.x
    node.position[1] = params.y

    this.update()
  }

  onDrag(dx: number, dy: number) {
    const x = this._startPosition[0] + dx
    const y = this._startPosition[1] + dy

    this.translate(x, y)
  }

  applyZoom(zoom: number) {
    this.size = nodeSize / zoom / nodeSize
    this.update()
  }

  update() {
    const [x, y] = this.node.position
    // this.el.style.transform = `translate(${x}px, ${y}px) scale(${this.size})`
    this.el.style.transform = `translate(${x}px, ${y}px)`
    this.el.style.setProperty('--pin-size', `${nodeSize * this.size}px`)

    if (this.selected) {
      this.el.classList.add('selected')
    } else {
      this.el.classList.remove('selected')
    }
  }
}
