import { Point } from "./point";
import { clamp } from "./math";


//todo: consider caching some stuff for performance
export class Path{
  points: Point[]

  constructor(...points : Point[]){
    this.points = points
  }

  calculateLength(): number{
    length = 0
    for(let i=1;i<this.points.length;i++){
      length += this.points[i-1].to(this.points[i]).length()
    }
    return length
  }

  /// point on the path in normalized 0-1 space
  calculateRelativePoint(relativePathDistance: number): Point{
    relativePathDistance = clamp(relativePathDistance, 0, 1)
    let length = this.calculateLength()
    let absolutePathDistance = relativePathDistance * length
    return this.calculateAbsolutePoint(absolutePathDistance)
  }

  calculateAbsolutePoint(absolutePathDistance: number): Point{
    for(let i=1;i<this.points.length;i++){
      let segmentVector = this.points[i-1].to(this.points[i])
      let segmentLength = segmentVector.length();
      if(absolutePathDistance <= segmentLength){
        let relativeSegmentPos = absolutePathDistance / segmentLength
        return this.points[i-1].add(segmentVector.scale(relativeSegmentPos))
      }
      absolutePathDistance -= segmentLength
    }
    return this.points[this.points.length-1]
  }
}