import Game from '../core/game'
import { intersect, length, subtract } from '../core/vector2'

class Walls {
    constructor (data) {
        this.walls = []
    }

    init (data) {
        data.forEach(part => {
            for (let i = 0; i < part.length - 2; i += 2) {
                this.walls.push([
                    [part[i], part[i + 1]],
                    [part[i + 2], part[i + 3]]
                ])
            }
        })

        Game.func('isIntersected', (v1, v2) => this.isIntersected(v1, v2))
        Game.func('findIntersect', (v1, v2) => this.findIntersect(v1, v2))
    }

    isIntersected (v1, v2) {
        const fn = wall => intersect(v1, v2, wall[0], wall[1])
        return this.walls.some(fn)
    }

    findIntersect (v1, v2) {
        const fn = wall => intersect(v1, v2, wall[0], wall[1])

        const result = this.walls.reduce((result, wall) => {
            const intersect = fn(wall)
            if (intersect) {
                const distance = length( subtract(intersect, v1) )

                if (!result || distance < result.distance) {
                    return {
                        intersect,
                        distance
                    }
                }
            }

            return result
        }, null)

        return result ? result.intersect : null
    }

    draw (ctx) {
        ctx.beginPath()
        ctx.strokeStyle = 'red'

        this.walls.forEach(wall => {
            ctx.moveTo(wall[0][0], wall[0][1])
            ctx.lineTo(wall[1][0], wall[1][1])
        })
        ctx.stroke()
        ctx.closePath()
    }
}

export default new Walls()
