import Game from '../core/game'
import Weapon from '../classes/weapon'
import vector from '../core/pipe'

import { angle } from '../core/vector2'

const { PI } = Math

export default class Unit {
    constructor (position, color = 'red') {
        this.radius = 4
        this.color = color

        this.position = position
        this.direction = [0, 1]
        this.velocity = [0, 0]
        this.acceleration = [0, 0]
        this.friction = .8

        this.firing = false
        this.crouch = false

        this.health = 100
        this.killed = false

        this.weapon = new Weapon(this)

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

    draw (ctx) {
        this.weapon.draw(ctx)

        ctx.save()
        ctx.translate(this.position[0], this.position[1])
        ctx.rotate(angle(this.direction))

        ctx.beginPath()
        ctx.arc(0, 0, this.radius, 0, 2 * PI, false)
        ctx.fillStyle = this.color
        ctx.fill()
        ctx.lineWidth = 1
        ctx.strokeStyle = '#000000'
        ctx.stroke()
        ctx.closePath()

        ctx.beginPath()
        ctx.fillStyle = '#fff'

        ctx.moveTo(this.radius * 1.3, 0)
        ctx.lineTo(this.radius * .7, this.radius - this.radius / 3)
        ctx.lineTo(this.radius * .7, - (this.radius - this.radius / 3))

        ctx.fill()
        ctx.closePath()
        ctx.restore()
    }

    lookAt (pos) {
        // this.direction = unit(subtract(pos, this.position))
        this.direction = vector(pos).subtract(this.position).unit().val()
    }

    move (dt) {
        this.weapon.action(dt)

        // dt ???????
        const speed = 15
        const maxSpeed = this.crouch ? 6 : 15

        const acceleration = vector(this.acceleration).scale(speed).limit(maxSpeed).val()
        this.velocity = vector(this.velocity).add(acceleration).scale(this.friction).val()
        const newPosition = vector(this.velocity).scale(dt).add(this.position).val()

        const intersect = this.intersectWall(this.position, newPosition)
        if (intersect) {
            this.velocity = [0,0]
        } else {
            this.position = newPosition
        }
    }
}
