"use strict";
this.name = "smShipSubentity";
this.author = "Eric Walch";
this.copyright = "august2008";
this.description = "Code that adds a loose subentity at the position of a killed subentity.";
this.version = "1.07";

//-------------------------------------------------------------------------------------------------------------
this.shipDied = function () {
    if (this.ship.isSubEntity) {
        var mom = this.ship.owner;
        if ((this.ship.entityPersonality ^ 15) & 15 > 12) {
            var subent = this.ship.owner.spawnOne(this.ship.primaryRole);
            if (subent.isValid) {
                subent.orientation = mom.orientation;
                subent.position = this.localToGlobal(this.ship.position.multiply(1.1), mom);
                subent.velocity = mom.velocity.multiply(0.7);
            }
        }
        else if (this.ship.mass > 1000 && (this.ship.entityPersonality & 15 < 4)) {
            mom.spawn("alloy", Math.ceil(Math.random() * (Math.log(this.ship.mass) - 5)));
        }
        // if (mom.subEntities.length == 1) mom.reactToAIMessage("ENERGY_LOW"); // last sub is shot away.
    }
    else {
        if (this.ship.mass > 1000 && Math.random() < 0.2) this.ship.spawnOne("alloy");
        if (this.timer) { this.timer.stop(); delete this.timer };
    }
    delete this.shipDied;
}

//-------------------------------------------------------------------------------------------------------------
this.localToGlobal = function (position, ship) {
    var orientation = ship.orientation;
    if (0 < oolite.compareVersion("1.75")) orientation.w = -orientation.w;
    return ship.position.add(position.rotateBy(orientation));
}

//-------------------------------------------------------------------------------------------------------------
this.countdown = function () { // called by AI
    if (Math.random() > 0.05) this.timer = new Timer(this, this.$die.bind(this), Math.random() * 1.3 + 0.2);
}

//-------------------------------------------------------------------------------------------------------------
this.$die = function $die() {
    this.ship.reactToAIMessage("SUBENT_DIED");
}

//-------------------------------------------------------------------------------------------------------------
this.entityDestroyed = function () {
    if (this.timer) { this.timer.stop(); delete this.timer };
}
