import State from '../state'
import config from '../../config'
import keys from '../../cgt/inputs/keyboard'
import screen from './screen'

const userHas = item => {
    return config.player().items.indexOf(item) >= 0
}

let CheckKey = null

class UserState extends State {
    init() {

    }

    draw(ctx) {
        screen.render(ctx)
    }

    update() {
        if (CheckKey) {
            if (keys.get(CheckKey)) {
                return
            }
            CheckKey = null
        }
        // this.emit('done')

        if (keys.get('DOWN')) {
            CheckKey = 'DOWN'
            if (!this.items.length) {
                this.selected = -1
            } else {
                this.selected++
                if (! this.items[this.selected]) this.selected = 0
            }
            return
        }

        if (keys.get('UP')) {
            CheckKey = 'UP'
            if (!this.items.length) {
                this.selected = -1
            } else {
                this.selected--
                if (! this.items[this.selected]) this.selected = this.items.length - 1
            }
            return
        }

        if (keys.get('A')) {
            CheckKey = 'A'

            const action = this.items[this.selected]
            if (action === 'Выстрелить') {
                this.emit('done', {
                    action: 'fire',
                    delay: 5
                })
            }

            if (action === 'Иcпользовать аптечку') {
                this.emit('done', {
                    action: 'health',
                    delay: 2
                })
            }

            if (action === 'Замедлить') {
                this.emit('done', {
                    action: 'slow',
                    delay: 10
                })
            }

            if (action === 'Убежать') {
                this.emit('done', {
                    action: 'run',
                    delay: 7
                })
            }

            return
        }

        screen.setMarker( this.selected )
    }

    prepare() {
        this.items = []

        if ( userHas('плазменный резак') )
            this.items.push('Выстрелить')

        if ( userHas('аптечка') )
            this.items.push('Иcпользовать аптечку')

        if ( userHas('стазис модуль') )
            this.items.push('Замедлить')

        this.items.push('Убежать')

        screen.setText( this.items )

        this.selected = this.items.length ? 0 : -1
        screen.setMarker( this.selected )
    }
}

export default UserState
