﻿// handles score, lives, level tracking
LevelManager.LEVEL = 1;
LevelManager.LIVES = 0;

function LevelManager()
{
    this.init();
    EventCenter.addListener(this, Events.NEXT_LEVEL, "nextLevel");
    EventCenter.addListener(this, Events.ENEMY_HIT, "setScore");
    EventCenter.addListener(this, Events.SHIP_HIT, "setLives");
}

LevelManager.prototype.init = function()
{
    this.level = 1;
    this.score = 0;
    this.newLives = 0;
    LevelManager.LIVES = this.lives = Settings.STARTING_LIVES;
    this.nextLife = Settings.BASE_NEXT_LIFE;
    this.basePoints = Settings.BASE_ENEMY_POINTS;
    this.highScore = Settings.BASE_HI_SCORE;
    this.enemyTypes = Settings.ENEMY_TYPE_COUNT;
    this.sendData();
}

LevelManager.prototype.nextLevel = function()
{
    LevelManager.LEVEL = ++this.level;
}

LevelManager.prototype.setScore = function(evt)
{
    var type = evt.data;
    var points = Math.round(type / this.enemyTypes * this.basePoints);
    this.score += points;
    if(this.score > this.highScore) this.highScore = this.score;
    if(this.score >= this.nextLife) this.setLives(true);
    this.sendData();
}

LevelManager.prototype.setLives = function(newLife)
{
    if(newLife == true)
    {
        LevelManager.LIVES = ++this.lives;
        this.newLives++;
        this.nextLife *= this.newLives + 1;
    }
    else
    {
        LevelManager.LIVES = --this.lives;
        if(this.lives <= 0)
        {
            LevelManager.LIVES = this.lives = Settings.STARTING_LIVES;
            EventCenter.broadcast(Events.GAME_OVER); 
        }
    }
   this.sendData();
}

LevelManager.prototype.sendData = function()
{
    EventCenter.broadcast(Events.SCORES, {score:this.score, highScore:this.highScore, lives:this.lives});
}
