export class RangeTreeMap {
    constructor() {
        /**
         * @type {Map<number, SimpleSegment[]>}
         */
        this.horizontal = new Map();
        
        /**
         * @type {Map<number, SimpleSegment[]>}
         */
        this.vertical = new Map();
    }

    /**
     * @param {SimpleSegment} segment 
     */
    insert(segment) {
        if (segment.x1 === segment.x2) {
            // 竖直线
            const x = segment.x1;
            if (!this.vertical.has(x)) {
                // TODO: 优化这里
                this.vertical.set(x, []);
            }
            this.vertical.get(x).push(segment);
        } else {
            // 水平线
            const y = segment.y1;
            if (!this.horizontal.has(y)) {
                // TODO: 优化这里
                this.horizontal.set(y, []);
            }
            this.horizontal.get(y).push(segment);
        }
    }


    /**
     * @description 计算给定点的度
     * @param {SimplePoint} point
     */
    getDegree(point) {
        // 分别从两个方向进行统计
        const x = point.x;
        const y = point.y;

        let degree = 0;
        const horizontalSegments = this.horizontal.get(y) || [];
        const verticalSegments = this.vertical.get(x) || [];

        let horizontalStartLocation = 0;
        let horizontalEndLocation = 0;
        let verticalStartLocation = 0;
        let verticalEndLocation = 0;

        for (const segment of horizontalSegments) {
            const x1 = Math.min(segment.x1, segment.x2);
            const x2 = Math.max(segment.x1, segment.x2);
            if (x1 <= x && x <= x2) {
                degree ++;
            }

            if (x1 === x) {
                horizontalStartLocation ++;
            }

            if (x2 === x) {
                horizontalEndLocation ++;
            }
        }

        for (const segment of verticalSegments) {
            const y1 = Math.min(segment.y1, segment.y2);
            const y2 = Math.max(segment.y1, segment.y2);
            if (y1 <= y && y <= y2) {
                degree ++;
            }

            if (y1 === y) {
                verticalStartLocation ++;
            }

            if (y2 === y) {
                verticalEndLocation ++;
            }
        }

        if (horizontalStartLocation > 1) {
            degree -= horizontalStartLocation - 1;
        }

        if (horizontalEndLocation > 1) {
            degree -= horizontalEndLocation - 1;
        }

        if (verticalStartLocation > 1) {
            degree -= verticalStartLocation - 1;
        }

        if (verticalEndLocation > 1) {
            degree -= verticalEndLocation - 1;
        }

        return degree;
    }
}


/**
 * @typedef SimpleSegment
 * @property {number} x1
 * @property {number} y1
 * @property {number} x2
 * @property {number} y2
 */

/**
 * @typedef SimplePoint
 * @property {number} x
 * @property {number} y
 */