const eps = 0.0000001

import Vector from './vector'
import Pair from './pair'

export const intersectVectors = (v1, v2, v3, v4) => {
    const a1 = v2.y - v1.y
    const b1 = v1.x - v2.x
    const c1 = (v2.x * v1.y) - (v1.x * v2.y)

    const r3 = ((a1 * v3.x) + (b1 * v3.y) + c1)
    const r4 = ((a1 * v4.x) + (b1 * v4.y) + c1)

    if ((r3 != 0) && (r4 != 0) && ((r3 * r4) >= eps)) {
        return null
    }

    const a2 = v4.y - v3.y
    const b2 = v3.x - v4.x;
    const c2 = (v4.x * v3.y) - (v3.x * v4.y);

    const r1 = (a2 * v1.x) + (b2 * v1.y) + c2;
    const r2 = (a2 * v2.x) + (b2 * v2.y) + c2;

    if ((r1 != 0) && (r2 != 0) && ((r1 * r2) >= eps)) {
        return null
    }


    const denom = (a1 * b2) - (a2 * b1);

    if (denom == 0) {
        return null
    }

    const offset = denom < 0 ? -denom / 2 : denom / 2

    const numx = (b1 * c2) - (b2 * c1)
    const x = numx < 0 ? (numx - offset) / denom : (numx + offset) / denom

    const numy = (a2 * c1) - (a1 * c2)
    const y = numy < 0 ? (numy - offset) / denom : (numy + offset) / denom

    return Vector.of(x, y)
}

export const intersectPairs = (p1, p2) => intersectVectors(p1.start, p1.end, p2.start, p2.end)

export default {
    intersectVectors,
    intersectPairs
}