import State from '../state'
import config from '../../config'

import screen from './screen'

const movingTime = 200

class MovingState extends State {
    init() {
        this.dir = 0
    }

    setDirection(dir) {
        this.dir = dir
        this.offset = { x: 0, y: 0 }

        if (this.dir === 4) this.dtMove = { x: 0, y: -1 }
        else if (this.dir === 2) this.dtMove = { x: 1, y: 0 }
        else if (this.dir === 1) this.dtMove = { x: 0, y: 1 }
        else if (this.dir === 3) this.dtMove = { x: -1, y: 0 }
        else this.dtMove = { x: 0, y: 0 }

        this.startTime = Date.now()
    }

    newPlayerPos(dt) {
        const k = 8 * dt / movingTime
        this.offset.x = this.dtMove.x * k
        this.offset.y = this.dtMove.y * k
    }

    draw(ctx) {
        screen.setPlayerOffset(this.offset)
        screen.render(ctx)
    }

    update() {
        const dt = Date.now() - this.startTime

        if (dt >= movingTime) {
            this.newPlayerPos(movingTime)
            this.dir = 0
            config.player().position.x += this.dtMove.x
            config.player().position.y += this.dtMove.y
            this.offset = { x: 0, y: 0 }
            screen.setPlayerOffset(this.offset)
            this.emit('endmoving')
        }
        else {
            this.newPlayerPos(dt)
        }
    }
}

export default MovingState
