"use strict"

this.name = "sex_drive";
this.version = "1.0";
this.description = "Teleporting cheat script; plays nicely with Explorers Club.";

/* ====================================================================================
   Aspirational roadmap:

   V 1.1 - Explorers' Club OXP, player's choice for operating in systems being visited
           for the first time: disable Ex Club or disable teleportation. NO USING
           TELEPORT to log Ex Club visits. Must auto-reset as soon as player leaves the
           new system. Don't leave either OXP disabled on return to familiar systems.

			OPTIONS WE'LL SAVE BETWEEN GAMES

    _myButton stores the option of torus, injectors, hostiles or low energy to teleport.
    _myExClub is for V1.1 and is not used herein.
======================================================================================= */

    this._myButton = "off";
    this._myExClub = "NO_TELEPORT";

    this.startUp = function () {
        "use strict";
        if (missionVariables.SEX_Drive_button) {
            this._myButton = missionVariables.SEX_Drive_button;
        } else {
            mission.setInstructions("Familiarise yourself with the Special Equipment Experiment.", this.name);
            let e = worldScripts.EmailSystem;
            if (e) {
                e.$createEmail({sender: "Betty from Wildefire Systems", subject: "NON-DISCLOSURE AGREEMENT", date: clock.adjustedSeconds, sentFrom: 100, message: "Greetings Commander, \n\nI write to remind you that the Special Equipment (Experimental) we recently installed aboard your ship is subject to a very strict Non-Disclosure Agreement (NDA). You must not, under any circumstances, allow it to be examined by anyone other than specifically authorized personnel here at the Special Equipment programme. \n\nPlease report any difficulties, and welcome to our flight testing programme. \n\nBetty,\nTeam liaison, Wildefire SE"});
            }
        }
        if (missionVariables.SEX_Drive_exclub) {
            this._myExClub = missionVariables.SEX_Drive_exclub;
        }
     // delete this.startUp;
    }

    this.playerWillSaveGame = function () {
        "use strict";
        missionVariables.SEX_Drive_button = this._myButton;
        missionVariables.SEX_Drive_exclub = this._myExClub;
    }

/* ====================================================================================
			SETTING THE STATION INTERFACE
======================================================================================= */

    this.startUpComplete = function () {
        "use strict";
        if (player.ship.docked) {
            this._applyInterface(player.ship.dockedStation);
        }
     // delete this.startUpComplete;
    }

    this.shipDockedWithStation = function (station) {
        "use strict";
        if (this._teleportAllowed) {
            this._applyInterface(station);
        }
    }

    this._applyInterface = function (station) {
        "use strict";
        station.setInterface("sex_drive", {
            title: "Wildefire SE-X drive",
            category: expandDescription("[interfaces-category-ship-systems]"),
            summary: "Wildefire Systems have installed Special Equipment (experimental) aboard this vessel.",
            callback: this._myScreen.bind(this)
        });
    }

/* ====================================================================================
			REMOVING THE STATION INTERFACE &
                        CHECKING FOR EXPLORERS' CLUB STATUS
======================================================================================= */

    this.shipWillLaunchFromStation = function (station) {
        "use strict";
        station.setInterface("sex_drive", null);
        this._checkExClubStatus();
    }

    this.shipWillExitWitchspace = function () {
        "use strict";
        this._checkExClubStatus();
    }

    this._checkExClubStatus = function () {
        "use strict";
        var ws = worldScripts['Explorers Club'];
        if (ws && ws._playerVisited(galaxyNumber, system.ID)) {
            this._teleportAllowed = true;
            return true;
        } else {
            this._teleportAllowed = false;
            return false;
        }
    }

/* ====================================================================================
			FINALLY GETTING TO THE NITTY-GRITTY

 When entering a new system, this._updatedTarget = false must be reset. The compass
 always resets to planet mode, but compassTargetChanged can take a while to occur, so
 if _updatedTarget remains true, the player can teleport into a planet.
======================================================================================= */

    this.shipLaunchedFromStation = this.shipExitedWitchspace = function () {
        "use strict";
        if (this._teleportAllowed) {
            if (!this._sexyTime) {
                this._sexyTime = new Timer(this, this._monitorState.bind(this), 0, 0.50);
            }
        }
        this._validTarget = false;
        this._updatedTarget = false;
    }

    this.shipWillDockWithStation = this.shipWillEnterWitchspace = function () {
        "use strict";
        if (this._sexyTime) {
            this._sexyTime.stop();
            delete this._sexyTime;
        }
    }

/* ====================================================================================
		THE FOLLOWING TWO FUNCTIONS ARE THE ACTUAL TELEPORTER
======================================================================================= */

    this.compassTargetChanged = function (whom, mode) {
        "use strict";
        if (this._teleportAllowed) {
            if (mode === "COMPASS_MODE_BASIC") {
                if (whom && whom.isMainStation) {
                    mode = "COMPASS_MODE_STATION";
                } else {
                    mode = "COMPASS_MODE_PLANET";
                }
            }
            if (mode === "COMPASS_MODE_PLANET" || mode === "COMPASS_MODE_SUN") {
                return;
            }

         // Teleporting into a planet or star ends badly.
         // If we reach here, whom is a beacon or target,
         // not a celestial body. Check that whom hasn't
         // suffered a tragedy in the last few moments...

            if (whom && whom.isValid) {
                if (whom != this._validTarget) {
                    this._validTarget = whom;
                    this._updatedTarget = true;
                    player.consoleMessage("SE-X: " + whom.displayName, 6);
                }
            }
        }
    }

    this._monitorState = function () {
        "use strict";
        if (this._teleportAllowed && this._updatedTarget) {
            var ps = player.ship;
            var goNow = false;
            switch (this._myButton) {
              case "torusEngaged":
                if (ps.torusEngaged) {
                    goNow = true;
                }
                break;
              case "injectorsEngaged":
                if (ps.injectorsEngaged) {
                    goNow = true;
                }
                break;
              case "alertHostiles":
                if (player.alertHostiles) {
                    goNow = true;
                }
                break;
              case "alertEnergy":
                if (player.alertEnergy) {
                    goNow = true;
                }
                break;
              default:
                return; // This should not happen.
            }
            if (goNow) {
                if (this._validTarget && this._validTarget.isValid) {
                    this._updatedTarget = false;
                    player.consoleMessage("SE-X drive engaged.", 9);
                    ps.position = this._validTarget.position;
                    player.consoleMessage("Arrived at " + this._validTarget.displayName, 9);
                }
            }
        }
    }

/* ====================================================================================
			MISSION SCREEN FOR SELECTING OPTIONS

 TO-DO: Clean up the mission screen, which is still scruffy. The screen should show the
 currently selected options, and re-appear at least once. Using the commsMessage is a
 n00b hack. Also, there has to be a better way than guiScreenChanged to restore the HUD.
======================================================================================= */

    this._myScreen = function () {
        "use strict";
        mission.setInstructions(null, this.name);
        if (player.ship.hudHidden === false) {
            this._hudWasVisible = true;
            player.ship.hudHidden = true;
	}
        var parameters = new Object;
        parameters.screenID = "SEX_DRIVE_OPTIONS_SCREEN";
        parameters.allowInterrupt = true;
        parameters.exitScreen = "GUI_SCREEN_INTERFACES";
        parameters.background = {name: "Betty_from_Wildefire_Systems.png", height: 480};
        parameters.title = "Wildefire Systems";
        parameters.messageKey = "sex_drive_message";
        parameters.choicesKey = "sex_drive_choices";
        mission.runScreen(parameters, callback);
    
        function callback(choice) {
            if (choice === "10__torus") {
                this._myButton = "torusEngaged";
            } else if (choice === "20__injectors") {
                this._myButton = "injectorsEngaged";
            } else if (choice === "30__hostiles") {
                this._myButton = "alertHostiles";
            } else if (choice === "40__energy") {
                this._myButton = "alertEnergy";
            } else if (choice === "50__exclub") {
                this._myExClub = "NO_EXCLUB";
            } else if (choice === "60__exclub") {
                this._myExClub = "NO_TELEPORT";
            }
            player.commsMessage("Your selected options were " + this._myButton + " and " + this._myExClub + ".", 10);
        }
    
    }

/* ====================================================================================
			RESTORING THE HUD AFTER MISSION SCREEN
======================================================================================= */

    this.guiScreenChanged = function (to, from) {
        "use strict";
        if (from === "GUI_SCREEN_MISSION" && this._hudWasVisible) {
            player.ship.hudHidden = false;
            delete this._hudWasVisible;
        }
    }

/* ====================================================================================
			THE END. REMEMBER, CHEATING IS WRONG, OKAY.
======================================================================================= */
