export class Polyline {
    constructor(points) {
        this.sections = [];
        this.points = points.map(({ x, y }) => [x, y]);
        for (let i = 0; i < this.points.length - 1; i++) {
            const p1 = this.points[i];
            const p2 = this.points[i + 1];
            const size = this.distance(p1, p2);
            this.sections.push({ p1, p2, size });
        }
    }
    /**
     * Returns the size of the polyline.
     */
    get size() {
        return this.sections.reduce((total, { size }) => total + size, 0);
    }
    /**
     * Returns the middle of the polyline.
     */
    get middle() {
        // Middle of the line in terms of size
        const target = this.size / 2;
        // Move along sections until we find the section that exceeds our target,
        // from this section we can calculate the middle point's coordinated.
        let cur = 0;
        for (const section of this.sections) {
            const next = cur + section.size;
            if (next > target)
                return this.along(section, target - cur);
            cur = next;
        }
        // Polyline has no sections
        return [0, 0];
    }
    /**
     * Moves along the section by the specified distance.
     * @param section
     * @param distance
     */
    along(section, distance) {
        const [x1, y1] = section.p1;
        const [x2, y2] = section.p2;
        const k = distance / section.size;
        return [k * x2 + (1 - k) * x1, k * y2 + (1 - k) * y1];
    }
    /**
     * Calculate the distance between two points.
     * @param p1 Start point
     * @param p2 End point
     */
    distance([x1, y1], [x2, y2]) {
        const horDistance = Math.pow(x2 - x1, 2);
        const verDistance = Math.pow(y2 - y1, 2);
        return Math.sqrt(horDistance + verDistance);
    }
}
