import * as RE from 'rogue-engine'
import * as THREE from 'three'
import {LineGeometry} from 'three/examples/jsm/lines/LineGeometry'
import {LineMaterial} from 'three/examples/jsm/lines/LineMaterial'

import {Line2} from 'three/examples/jsm/lines/Line2'

export default class Pathway extends RE.Component {
  linePoints = []

  colors = []

  @RE.props.color()
  lineColorShift = new THREE.Color(0.1, 0.1, 0.1)

  awake() {
  }

  start() {
    this.lineGeo = new LineGeometry();
    this.lineMat = new LineMaterial({

        color: 0xffffff,
        linewidth: 5, // in pixels
        vertexColors: true,
        dashed: false,
        wireframe: false,

    });

    const bounds = RE.Runtime.rogueDOMContainer.getBoundingClientRect();
    this.lineMat.resolution.set(bounds.width, bounds.height);
  }

  updateGeometry() {
    if(this.linePoints.length < 2) {
      return
    }

    const positions = [];
		const colors = []
	
		for (let p of this.linePoints) {
		  positions.push(p.x, p.y, p.z);
		}

    for (let c of this.colors) {
		  colors.push(Math.min(1, c.r + this.lineColorShift.r), Math.min(1, c.g + this.lineColorShift.g), Math.min(1, c.b + this.lineColorShift.b));
		}

    this.lineGeo = new LineGeometry();
    this.lineGeo.setPositions(positions)
    this.lineGeo.setColors(colors)

    if(this.line) {
      RE.App.currentScene.remove(this.line)
    }
    this.line = new Line2(this.lineGeo, this.lineMat);
    this.line.scale.set(1, 1, 1);
    
    RE.App.currentScene.add(this.line)
    this.line.computeLineDistances();
    
	}

  addPoint(position, color) {
    let dupePosition = position.clone()
    dupePosition.y -= 4
    dupePosition.z += 0.1
    this.linePoints.push(dupePosition)
    this.colors.push(color)
    this.updateGeometry()
  }

  recomputePath(tileComponents) {
    this.clearPoints()
    tileComponents.forEach((tileComponent, index) => {
      this.addPoint(tileComponent.object3d.position, tileComponent.object3d.originalMaterial.color)
    })
    this.updateGeometry()
  }

  clearPoints() {
    this.linePoints.length = 0
    this.colors.length = 0
    if(this.line) {
      RE.App.currentScene.remove(this.line)
    }
  }

  update() {
  }
}

RE.registerComponent(Pathway);
