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

this._targetSystem = -2;
this._sourceSystem = -1;
this._missionShip = null;
this._messages = [];
this._checkForRefueling = false;
this._dist = 0;
this._holdShipName = "";

//-------------------------------------------------------------------------------------------------------------
this.startUp = function () {
    if (missionVariables.LaveMission_SourceSystemID) {
        this._sourceSystem = missionVariables.LaveMission2_SourceSystemID;
    }
    if (missionVariables.LaveMission_TargetSystemID) {
        this._targetSystem = missionVariables.LaveMission2_TargetSystemID;
    }
    if (this._sourceSystem != -1 && this._targetSystem != -2) {
        this.$setupFunctions();
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$setupMission = function () {
    // pick a system within 7 ly of current.
    var syslist = system.info.systemsInRange(7);
    var sys = syslist[parseInt(Math.random() * syslist.length)];
    this._targetSystem = sys.systemID;
    this._sourceSystem = system.ID;

    missionVariables.LaveMission2_SourceSystemID = system.ID;
    missionVariables.LaveMission2_SourceSystem = system.name;
    missionVariables.LaveMission2_TargetSystemID = this._targetSystem;

    this.$setupFunctions();
}

//-------------------------------------------------------------------------------------------------------------
this.$setupFunctions = function () {
    this.systemWillPopulate = this.systemWillPopulate_hold;
    this.missionScreenOpportunity = this.missionScreenOpportunity_hold;
    this.playerEnteredNewGalaxy = this.playerEnteredNewGalaxy_hold;
    this.playerWillEnterWitchspace = this.playerWillEnterWitchspace_hold;

    mission.setInstructionsKey(this.name + "_instructions", this.name);
}

//-------------------------------------------------------------------------------------------------------------
this.$cleanUp = function () {
    this._targetSystem = -2;
    if (this._progress && this._progress.isRunning) this._progress.stop();
    delete missionVariables.LaveMission2_SourceSystem;
    delete missionVariables.LaveMission2_TargetSystemID;
    delete missionVariables.LaveMission2_SourceSystemID;
    delete this.systemWillPopulate;
    delete this.missionScreenOpportunity;
    delete this.playerEnteredNewGalaxy;
    delete this.playerWillEnterWitchspace;
}

//-------------------------------------------------------------------------------------------------------------
this.playerWillEnterWitchspace = function () {
    if (this._progress && this._progress.isRunning) this._progress.stop();
}

//-------------------------------------------------------------------------------------------------------------
this.systemWillPopulate_hold = function () {
    if (system.ID == this._targetSystem) {
        this._missionShip = system.addShips("trainee_lost1", 1, [0, 0, 0], 5000)[0];
        this._progress = new Timer(this, this.$checkProgress.bind(this), 10, 5);
    }
    if (system.ID == this._sourceSystem && worldScripts.lave_missions._missionStatus["mission_2"] == "FOUND") {
        this._missionShip = system.addShips("trainee_lost2", 1, [0, 0, 0], 5000)[0];
        this._delay = new Timer(this, this.$sendFlightHome, 3, 0);
        if (this._holdShipName != "") {
            this._missionShip.displayName = this._holdShipName;
        }
    }
}

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

//-------------------------------------------------------------------------------------------------------------
this.missionScreenOpportunity_hold = function () {
    if (player.ship.dockedStation.dataKey == "laveAcademy_academy") {
        var status = worldScripts.lave_missions._missionStatus["mission_2"];
        if (status == "NOT_STARTED" || status == "FINISHED" || status == "STARTED") return; // player redocked for some reason
        // otherwise, we're finished
        switch (status) {
            case "FAILED":
                mission.runScreen({ title: expandMissionText("lave_mission_2_title_1"), messageKey: "lave_mission_2_failed", screenID: "lave_missions" });
                break;
            case "FOUND":
                // trainee hasn't docked yet
                return;
            case "COMPLETE":
                mission.runScreen({ title: expandMissionText("lave_mission_2_title_2"), messageKey: "lave_mission_2_complete", screenID: "lave_missions" });
                player.credits += 1000;
                break;
        }
        worldScripts.lave_missions._missionStatus["mission_2"] = "FINISHED";
        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() {
    if (system.ID == this._targetSystem) {
        if (worldScripts.lave_missions._missionStatus["mission_2"] == "STARTED" && this._missionShip.position.distanceTo(player.ship) < player.ship.scannerRange * 0.8) {
            worldScripts.lave_missions._missionStatus["mission_2"] = "FOUND";
            mission.setInstructionsKey(this.name + "_instructions_found", this.name);
            if (this._holdShipName == "") this._holdShipName = this._missionShip.displayName;
            this._dist = system.info.distanceToSystem(System.infoForSystem(galaxyNumber, this._sourceSystem));
            if (player.ship.fuel < this._dist) {
                // offer some fuel to player
                this._messages = expandMissionText("lave_mission_2_offerfuel").split("|");
                this._checkForRefueling = true;
            } else {
                // thank player for coming
                this._messages = expandMissionText("lave_mission_2_thanksforhelp").split("|");
            }
        }
    }
    if (this._messages.length > 0 && this._missionShip.position.distanceTo(player.ship) < player.ship.scannerRange) {
        var text = this._messages.shift();
        this._missionShip.commsMessage(text, player.ship);
    }
    if (this._checkForRefueling == true && player.ship.fuel < this._dist && this._missionShip.position.distanceTo(player.ship) <= 86) {
        player.consoleMessage(expandMissionText("lave_mission_2_fuel"), 4);
        player.ship.fuel += 1;
    }
    if (this._checkForRefueling == true && player.ship.fuel >= this._dist) {
        this._checkForRefueling = false;
        this._missionShip.commsMessage(expandMissionText("lave_mission_2_comms_1"), player.ship);
        this._messages = [expandMissionText("lave_mission_2_comms_2")];
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$updateStatus = function () {
    mission.setInstructionsKey(this.name + "_instructions_complete", this.name);
}

//-------------------------------------------------------------------------------------------------------------
this.$sendFlightHome = function $sendFlightHome() {
    var stnLoc = system.shipsWithRole("laveAcademy_academy")[0];
    // check if we got an actual ship location returned
    if (stnLoc) {
        if (this._missionShip.isValid) {
            // send ship back to academy
            this._missionShip.AIScript.oolite_priorityai.setParameter("oolite_selectedPlanet", null);
            this._missionShip.AIScript.oolite_priorityai.setParameter("oolite_selectedStation", stnLoc);
            this._missionShip.AIScript.oolite_priorityai.reconsiderNow();
        }
    }
}