// https://evanw.github.io/lightgl.js/docs/vector.html

const { sin, cos, sqrt, atan2, abs } = Math
const eps = 0.0000001
const hypot = Math.hypot || ((a, b) => sqrt(a*a + b*b))

export default class Vector {
    constructor (x = 0, y = 0) {
        this.x = x
        this.y = y
    }

    static of (x, y) {
        return new Vector(x, y)
    }

    xy (x, y) {
        this.x = x
        this.y = y
        return this
    }

    copy () {
        return Vector.of(this.x, this.y)
    }

    dot (v) {
        return this.x * v.x + this.y * v.y
    }

    mag () {
        return hypot(this.x, this.y)
    }

    unit () {
        return this.divide(this.mag())
    }

    add (vec) {
        this.x += vec.x
        this.y += vec.y
        return this
    }

    addXY (x, y) {
        this.x += x
        this.y += y
        return this
    }

    subtract (vec) {
        this.x -= vec.x
        this.y -= vec.y
        return this
    }

    multiply (l) {
        this.x *= l
        this.y *= l
        return this
    }

    divide (l) {
        this.x /= l
        this.y /= l
        return this
    }

    rotate(angle) {
        const x = this.x * cos(angle) - this.y * sin(angle)
        const y = this.x * sin(angle) + this.y * cos(angle)

        this.x = x
        this.y = y

        return this
    }

    limit (max) {
        const l = this.mag()
        if (l > max) {
            this.divide(l).multiply(max)
        }
        return this
    }

    angle () {
        return atan2(this.y , this.x)
    }

    fromAngle (angle, magnitude) {
        return new Vector(magnitude * cos(angle), magnitude * sin(angle))
    }

}
