import Vector from './vector'
import { intersectPairs } from './intersect'

class Colliders {

    constructor() {
        this.objects = []
    }

    add(object) {
        this.objects.push(object)
    }

    hasCollision(way, objects = this.objects) {
        return objects.some(object => intersectPairs(way, object) !== null)
    }

    findCollision(way, objects = this.objects) {
        const nearestCollision = objects.reduce((result, object) => {
            const collision = intersectPairs(way, object)
            if (collision) {
                const distance = way.start.copy().subtract(collision).length()

                if (!result || distance < result.distance) {
                    return {
                        collision,
                        distance
                    }
                }
            }
        })
        return nearestCollision ? nearestCollision.collision : null
    }
}

export default new Colliders()
