// the duck-spawner entity sits in a figurative corner and decides when to spawn ducks
// levels that have ducks in them will have a duck spawner manageing them.
//
ig.module('game.entities.duck-spawner')
.requires(
    'game.entities.duck',
    'impact.impact'
)
.defines(function () {
    "use strict";
    ig.global.EntityDuckSpawner = ig.Entity.extend({
        maxDucks: 1,
        minSpawnTime: 1,
        maxSpawnTime: 1,
        nextSpawnTime: 0.1,
        numDucks: 0,
        enabled: true,
        timer: new ig.Timer(),
        init: function (minTime, maxTime, maxDucks, settings) {
            this.maxDucks = maxDucks;
            this.minSpawnTime = minTime;
            this.maxSpawnTime = maxTime;
            //this is just an entity to take advantage of the update loop
            //so the position does not matter
            this.parent(0, 0, settings);
        },
        handleDuckDestroy: function () {
            this.numDucks = this.numDucks - 1;
            this.timer.reset();
        },
        update: function () {
            if (this.enabled) {
                if (this.timer.delta() > this.nextSpawnTime && this.numDucks < this.maxDucks && !ig.game.player.invincible) {
                    this.timer.reset();
                    this.numDucks += 1;
                    //generate a random value between minSpawnTime and maxSpawnTime
                    this.nextSpawnTime = Math.floor(Math.random() * (this.maxSpawnTime - this.minSpawnTime + 1) + this.minSpawnTime);

                    //generate a random number and use it to choose
                    //a random direction
                    var direction = Math.random();
                    if (direction >= 0.5) {
                        direction = "left";
                    } else {
                        direction = "right"
                    }
                    var ent = ig.game.spawnEntity(EntityDuck, 0, 0, direction);

                    ent.onRemove = this.handleDuckDestroy.bind(this);
                    var halfWidth = ig.system.width / 2;
                    if (direction === "right") {
                        ent.pos.x = 0 - ent.size.x;
                    } else {
                        ent.pos.x = ig.system.width + ent.size.x;
                    }
                    var floor = Math.round(Math.random() * 4);
                    ent.pos.y = ig.game.level.getPosition({ floor: floor, window: 0 }).y;
                }
                this.parent();
            }
        },
        draw: function () {
            if (this.enabled) {
                this.parent();
            }
        }
    });
});