import { NodeView } from './nodeview'

export type BoundingBox = {
  minX: number,
  maxX: number,
  minY: number,
  maxY: number,
  width: number,
  height: number,
}

export class NodeList {
  nodes = [] as NodeView[]
  viewport = { width: 0, height: 0 }
  public _selected = undefined as undefined | NodeView

  public set selected(nodeView: NodeView | undefined) {
    this._selected = nodeView

    this.nodes.forEach(n => {
      if (nodeView && n.node.id === nodeView.node.id) {
        n.selected = true
      } else {
        n.selected = false
      }

      n.update()
    })
  }

  getBoundingBox(padding = 60): BoundingBox {
    let minX = Number.MAX_SAFE_INTEGER
    let maxX = Number.MIN_SAFE_INTEGER
    let minY = Number.MAX_SAFE_INTEGER
    let maxY = Number.MIN_SAFE_INTEGER

    this.nodes.forEach(n => {
      minX = Math.min(minX, n.node.position[0])
      minY = Math.min(minY, n.node.position[1])
      maxX = Math.max(maxX, n.node.position[0])
      maxY = Math.max(maxY, n.node.position[1])
    })

    minX -= padding
    minY -= padding
    maxX += padding
    maxY += padding

    return {
      minX,
      maxX,
      minY,
      maxY,
      width: maxX - minX,
      height: maxY - minY,
    }
  }

  setViewport(data: { width: number, height: number }) {
    this.viewport = {
      width: data.width,
      height: data.height,
    }
  }

  getZoomToFit(bound: BoundingBox) {
    const width = bound.maxX - bound.minX
    const height = bound.maxY - bound.minY
    return Math.min(this.viewport.width / width, this.viewport.height / height)
  }
}
