import {hide, show} from '../helper.js';
import {Tool} from '../tool.js';
import {magnitude} from '../vector.js';

export class ObjectsTool extends Tool {
  objects = [];

  setContainer(container) {
    super.setContainer(container);

    // Display a list of the currently selected objects,
    // or all objects if none are currently selected.
    if (this.sim.select.selectedGroup.length) {
      this.objects = this.sim.select.selectedGroup;
    } else {
      this.objects = this.sim.system.filter(obj => obj.alive);
    }

    this.populate();

    this.sim.select.onSelect(({selectedGroup}) => {
      this.objects = selectedGroup;
      this.depopulate();
      this.populate();
    });

    this.sim.system.onCreate(obj => {
      if (!this.sim.select.selectedGroup.length) {
        this.objects.push(obj);
        this.populate();
      }
    });

    this.sim.system.onMerge(({merged}) => {
      if (!merged.objectsToolEl) return;
      hide({
        items: this.objects,
        item: merged,
        parentEl: this.div,
        itemEl: merged.objectsToolEl,
      });
    });
  }

  frame() {
    this.populate();
  }

  depopulate() {
    while (this.div.firstChild) {
      this.div.removeChild(this.div.firstChild);
    }
  }

  populate() {
    for (const obj of this.objects) {
      const objectEl = obj.objectsToolEl ?? document.createElement('div');
      obj.objectsToolEl = objectEl;
      const {r, g, b} = obj.color;
      // Distance from center of screen
      // const distance = magnitude(sub(obj.position, add(this.sim.display.viewOrigin, {
      // x: this.sim.display.width / 2,
      // y: this.sim.display.height / 2,
      // })));
      objectEl.innerHTML =
        `<span style="background-color: rgb(${r},${g},${b});">&nbsp;&nbsp;</span>` +
        `<div style="display:inline-block; vertical-align:middle; padding: 2px;">` +
        `E<sub>k</sub>: ${obj.kineticEnergy.toFixed(0)}<br>` +
        `|p|: ${magnitude(obj.momentum).toFixed(0)}<br>` +
        // `<br>&nbsp;&nbsp;W<sub>p</sub>: ${obj.workDoneByPointer.toFixed(0)}` +
        // `<br>&nbsp;&nbsp;W<sub>f</sub>: ${obj.workDoneByForces.toFixed(0)}`;
        '</div>';

      // `${obj.mass.toPrecision(3)} ` +
      // `${distance.toPrecision(3)}`;

      // `${magnitude(obj.velocity).toExponential(0)} ` +
      // `${-degrees(direction(obj.velocity)).toFixed(0)}°`;

      if (!obj.hidden) {
        show({
          items: this.objects,
          item: obj,
          parentEl: this.div,
          itemEl: objectEl,
        });
      }
    }
  }
}
