import Timeline from './timeline'
import config from '../../config'
import Scene from '../scene'

import UserState from './state-user'
import EnemyState from './state-enemy'
import StartState from './state-start'
import ActionState from './state-action'

import screen from './screen'

export default class Battle extends Scene {
    init() {
        screen.init()

        this.user = new UserState()
        this.user.on('done', ({action, delay}) => {
            this.timeline.add('player', action, delay)
            this.setNextState()
        })

        this.enemy = new EnemyState()
        this.enemy.on('done', () => {
            this.timeline.add('npc', 'attack', 10)
            this.setNextState()
        })

        this.end = new StartState()

        this.action = new ActionState()
        this.action.on('done', () => {
            if (config.player().health === 0) {
                this.end.prepare()
                this.setState(this.end)
            }

            else if (config.player().battle.health === 0) {
                this.setScene('map')
            }

            else {
                this.setNextState()
            }
        })
        this.action.on('run', () => {
            this.setScene('map')
        })

        this.timeline = new Timeline()

        this.setNextState()
    }

    setNextState() {

        const playerNextAction = this.timeline.unitNextAction('player')
        if (!playerNextAction) {
            this.user.prepare()
            this.setState(this.user)
            return
        }

        const npcNextAction = this.timeline.unitNextAction('npc')
        if (!npcNextAction) {
            this.enemy.prepare()
            this.setState(this.enemy)
            return
        }

        const action = this.timeline.next()
        this.action.prepare(action.action)
        this.setState(this.action)
    }
}
