import Game from '../core/game'
import vector from '../core/pipe'

import { add, rotate, scale } from '../core/vector2'

export default class Weapon {
    constructor (player, trackColor = 'red') {
        this.bullets = []
        this.tracks = []

        this.trackColor = trackColor

        this.player = player
        this.lastbullettime = 0

        this.recoilStart = 0
        this.recoilMax = 10 * Math.PI / 180
        this.range = 150
        this.firerate = 150

        this.recoil = this.recoilStart

        this.intersectWall = Game.func('findIntersect')
    }

    reset () {
        this.lastbullettime = 0
        this.recoil = this.recoilStart
    }

    draw (ctx) {
        ctx.fillStyle = 'white'
        this.bullets.forEach(bullet => {
            ctx.fillRect(bullet[0], bullet[1], 1, 1)
        })

        this.tracks.forEach(track => {
            const opacity = track.time * 2
            ctx.strokeStyle = 'rgba(255,255,255,' + opacity + ')'
            ctx.moveTo(track.start[0], track.start[1])
            ctx.lineTo(track.end[0], track.end[1])
            ctx.stroke()
        })

        this.tracks = this.tracks.filter(track => track.time > 0)

    }

    action (dt) {
        if (this.player.firing) {
            this.fire(this.player)
        }

        const decrementTime = track => {
            track.time -= dt
            return track
        }

        this.tracks = this.tracks
            .map(decrementTime)
            .filter(track => track.time > 0)
    }

    fire (unit) {
        const { position, direction } = unit

        if (Date.now() - this.lastbullettime < this.firerate) {
            return
        }

        const rand = this.recoil * (Math.random() * 2 - 1)

        // const target1 = add(rotate(scale(direction, this.range), rand), position)
        const target = vector(direction).scale(this.range).rotate(rand).add(position).val()

        this.recoil = Math.min(this.recoil + .1, this.recoilMax)

        const intersectWall = this.intersectWall(position, target)
        let unitIntersect = Game.func('unitIntersect')(position, intersectWall || target)
        if (unitIntersect && unitIntersect.unit === unit) {
            unitIntersect = null
        }

        if (unitIntersect) {
            Game.emit('unitfire', unitIntersect)
        } else {
            const b = Game.func('playerIntersect')(position, intersectWall || target)
            if (b && b != unit) {
                Game.emit('playerfire')
            } else {
                this.bullets.push(intersectWall || target)
            }
        }

        const trackEnd = (unitIntersect ? unitIntersect.position : null)
            || (unitIntersect && unitIntersect.unit ? unitIntersect.unit.position : null)
            || intersectWall
            || target

        this.tracks.push({
            start: position,
            end: trackEnd,
            time: .1
        })

        this.lastbullettime = Date.now()
    }
}
