"use strict";
this.name = "lave_mission_1";
this.author = "phkb";
this.copyright = "2024 phkb";
this.description = "Mission type 1 for Lave system";
this.license = "CC-BY-NC-SA 4.0";

this._missionShips = [];
this._pirates = [];
this._progress = null;
this._sentLastOneComms = false;

//-------------------------------------------------------------------------------------------------------------
this.startUpComplete = function () {
    var status = worldScripts.lave_missions._missionStatus["mission_1"];
    // check if the player has reloaded the game while it was in progress
    if (status == "STARTED") {
        this.$setupMission();
        return;
    }
    if (status == "FAILED" || status == "PARTIAL_COMPLETE" || status == "COMPLETE") {
        this.missionScreenOpportunity = this.missionScreenOpportunity_hold;
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$setupMission = function () {
    mission.setInstructionsKey(this.name + "_instructions", this.name);

    this.shipLaunchedFromStation = this.shipLaunchedFromStation_hold;
    this.missionScreenOpportunity = this.missionScreenOpportunity_hold;
    this.shipWillDockWithStation = this.shipWillDockWithStation_hold;
    this.shipWillEnterWitchspace = this.shipWillEnterWitchspace_hold;
    this.playerEnteredNewGalaxy = this.playerEnteredNewGalaxy_hold;
}

//-------------------------------------------------------------------------------------------------------------
this.$cleanUp = function () {
    delete this.shipLaunchedFromStation;
    delete this.missionScreenOpportunity;
    delete this.shipWillDockWithStation;
    delete this.shipWillEnterWitchspace;
    delete this.playerEnteredNewGalaxy;
}

//-------------------------------------------------------------------------------------------------------------
this.shipLaunchedFromStation_hold = function (station) {
    var pos = Vector3D.interpolate(system.sun.position, station.position, 0.66);

    // create the instructor flight and put them all in a group
    this._missionShips = system.addShips("instructor_mission", 1, pos, 1000);
    // make sure all the escorts are in the missionShips array
    for (var i = 0; i < this._missionShips[0].escorts.length; i++) {
        this._missionShips.push(this._missionShips[0].escorts[i]);
    }

    // create our pirates
    this._pirates = system.addShips("pirate", 4, pos, 10000);
    var prGroup = new ShipGroup("pirate_flight", this._pirates[0]);
    var i = this._pirates.length;
    while (i--) {
        // we're removing fuel injectors, because this mission gets messy if everything spreads out too much
        // and the player has to chase the bad guys too much
        this._pirates[i].removeEquipment("EQ_FUEL_INJECTION");
        prGroup.addShip(this._pirates[i]);
        this._pirates[i].group = prGroup;
        this._pirates[i].target = this._missionShips[parseInt(Math.random() * this._missionShips.length)];
        this._pirates[i].performAttack();
    }

    this._progress = new Timer(this, this.$checkProgress, 5, 5);
    delete this.shipLaunchedFromStation;
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillEnterWitchspace_hold = function () {
    if (worldScripts.lave_missions._missionStatus["mission_1"] == "STARTED") {
        worldScripts.lave_missions._missionStatus["mission_1"] = "FAILED";
        mission.setInstructionsKey(this.name + "_instructions_complete", this.name);
    }
}

//-------------------------------------------------------------------------------------------------------------
this.playerEnteredNewGalaxy_hold = function () {
    if (worldScripts.lave_missions._missionStatus["mission_1"] == "STARTED") {
        worldScripts.lave_missions._missionStatus["mission_1"] = "FINISHED";
        mission.setInstructionsKey(null, this.name);
        this.$cleanUp();
    }
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillDockWithStation_hold = function (station) {
    if (this._progress.isRunning) this._progress.stop();
    var status = worldScripts.lave_missions._missionStatus["mission_1"];
    if (status == "STARTED") {
        // have we finished but wasn't close enough to any of the mission ships to get the final message?
        var pr = this._pirates;
        var i = pr.length;
        while (i--) {
            // if there's at least one valid pirate left, it's still on
            // todo: check if they ran away - despawn them if they get too far from the mission ships
            if (pr[i] && pr[i].isValid) return;
        }
        var ms = this._missionShips;
        var i = ms.length;
        var deaths = 0;
        while (i--) {
            if (!ms[i] || !ms[i].isValid) deaths += 1;
        }
        if (deaths == ms.length) {
            worldScripts.lave_missions._missionStatus["mission_1"] = "FAILED";
        } else {
            worldScripts.lave_missions._missionStatus["mission_1"] = (deaths > 0 ? "PARTIAL_COMPLETE" : "COMPLETE");
        }
        mission.setInstructionsKey(this.name + "_instructions_complete", this.name);
        this.$sendFlightHome();
    }
}

//-------------------------------------------------------------------------------------------------------------
this.missionScreenOpportunity_hold = function () {
    if (player.ship.dockedStation.dataKey == "laveAcademy_academy") {
        var status = worldScripts.lave_missions._missionStatus["mission_1"];
        if (status == "NOT_STARTED" || status == "FINISHED" || status == "STARTED") return; // player redocked for some reason
        // otherwise, we're finished
        worldScripts.lave_missions._missionStatus["mission_1"] = "FINISHED";
        switch (status) {
            case "FAILED":
                mission.runScreen({ title: expandMissionText("lave_mission_1_title_1"), messageKey: "lave_mission_1_failed", screenID: "lave_missions" });
                break;
            case "PARTIAL_COMPLETE":
                mission.runScreen({ title: expandMissionText("lave_mission_1_title_2"), messageKey: "lave_mission_1_partial", screenID: "lave_missions" });
                player.credits += 200;
                break;
            case "COMPLETE":
                mission.runScreen({ title: expandMissionText("lave_mission_1_title_3"), messageKey: "lave_mission_1_complete", screenID: "lave_missions" });
                player.credits += 1000;
                break;
        }
        mission.setInstructionsKey(null, this.name);
        this.$cleanUp();
        worldScripts.lave_missions._checkForMission = false; // so we don't get asked about a new mission when we finish this one
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$checkProgress = function $checkProgress() {
    var pr = this._pirates;
    var i = pr.length;
    var enemies = 0;
    while (i--) {
        // if there's at least one valid pirate left, it's still on
        if (pr[i] && pr[i].isValid) {
            // todo: check if they ran away - despawn them if they get too far from the mission ships
            enemies += 1;
        }
    }
    if (enemies == 1 && this._sentLastOneComms == false) {
        this._sentLastOneComms = true;
        var sc = player.ship.checkScanner(true);
        i = sc.length;
        while (i--) {
            if (sc[i].roles.indexOf("lave_mission")) {
                sc[i].commsMessage(expandMissionText("lave_mission_1_comms_1"), player.ship);
                break;
            }
        }
    }
    if (enemies > 0) return;
    var ms = this._missionShips;
    var i = ms.length;
    var commSource;
    var deaths = 0;
    while (i--) {
        if (!ms[i] || !ms[i].isValid) {
            deaths += 1;
        } else {
            commSource = ms[i]; // get a reference to a valid ship object
        }
    }
    if (deaths == ms.length) {
        worldScripts.lave_missions._missionStatus["mission_1"] = "FAILED";
        this._progress.stop();
        return;
    }
    // we'd only get to this point if all the pirates are dead and at least 1 of the group is still alive
    // get one of the ships to send a message once they're in range
    if (commSource && commSource.isValid) {
        if (commSource.position.distanceTo(player.ship) < player.ship.scannerRange) {
            commSource.commsMessage(expandMissionText("lave_mission_1_comms_2"), player.ship);
            worldScripts.lave_missions._missionStatus["mission_1"] = (deaths > 0 ? "PARTIAL_COMPLETE" : "COMPLETE");
            mission.setInstructionsKey(this.name + "_instructions_complete", this.name);
            this._progress.stop();
        }
    }
    this.$sendFlightHome();
}

//-------------------------------------------------------------------------------------------------------------
this.$sendFlightHome = function () {
    if (this._missionShips.length == 0) return;
    var stnLoc = system.shipsWithRole("laveAcademy_academy")[0];
    // check if we got an actual ship location returned
    if (stnLoc) {
        if (this._missionShips[0].isValid) {
            this._missionShips[0].switchAI("oolite-shuttleAI.js");
            // send leader back to academy - escorts will follow so no need to do this for them
            this._missionShips[0].AIScript.oolite_priorityai.setParameter("oolite_selectedPlanet", null);
            this._missionShips[0].AIScript.oolite_priorityai.setParameter("oolite_selectedStation", stnLoc);
            this._missionShips[0].AIScript.oolite_priorityai.reconsiderNow();
        } else {
            // unless the leader is dead, so send all trainees back to the station individually
            for (var i = 1; i < this._missionShips.length; i++) {
                if (this._missionShips[i].isValid) {
                    this._missionShips[i].switchAI("oolite-shuttleAI.js");
                    this._missionShips[i].AIScript.oolite_priorityai.setParameter("oolite_selectedPlanet", null);
                    this._missionShips[i].AIScript.oolite_priorityai.setParameter("oolite_selectedStation", stnLoc);
                    this._missionShips[i].AIScript.oolite_priorityai.reconsiderNow();
                }
            }
        }
    }
}