"use strict";
this.name        = "Tionisla Reporter";
this.author      = "Eric Walch";
this.copyright   = "2011-2012 Eric Walch";
this.description = "worldScript for the erehwon mission";
this.licence     = "CC-by-NC-SA 3.0";

// Code adjusted by phkb to make Ewehwon appear in the same location any time the player misjumps between USLE and BIORLE
this._restoreIST = false;

//-------------------------------------------------------------------------------------------------------------
this.startUp = function (){
    //this.misjumpInfo = "";
    if (!missionVariables.erehwonReconnaissance) {
        missionVariables.erehwonReconnaissance = "START";
        missionVariables.erehwonFotoShot = "NO";
        missionVariables.erehwonGotStory = "NO";
        missionVariables.erehwomMisJumpInfo = "";
    } else if (missionVariables.erehwonReconnaissance == "FINISHED") {
        this.cleanUp();
    }
}

//-------------------------------------------------------------------------------------------------------------
this.missionScreenOpportunity = function (){
    if (!player.ship.docked || galaxyNumber != 0) return;
    this.missionOffers();
}

//-------------------------------------------------------------------------------------------------------------
this.missionOffers = function (){
    if (player.ship.dockedStation.isMainStation) {
        if (system.ID == 124) {
            if (missionVariables.erehwonReconnaissance == "START") {
                mission.runScreen({
					screenID:"tionisla_reporter",
                    titleKey: "tr_chronicle_title",
                    messageKey: "erehwonReconnaissance_briefing",
                    choicesKey: "erehwonReconnaissance_choice"
                    }, this.choiceEvaluation
                );
            }
            if (missionVariables.erehwonReconnaissance == "SUCCESS") {
                mission.runScreen({
					screenID:"tionisla_reporter",
                    titleKey: "tr_chronicle_title",
                    messageKey: "erehwonReconnaissance_debriefing",
                    model: "erehwonStation"
                    }
                );
                mission.displayModel.orientation = [0.75, 0, -0.6, 0];
                delete missionVariables.erehwonGotStory;
                delete missionVariables.erehwonFotoShot;
                delete missionVariables.erehwonPictureCount;
                //delete missionVariables.showErehwon;
                delete missionVariables.erehwomMisJumpInfo;
                missionVariables.erehwonReconnaissance = "EPILOGUE";
                missionVariables.erehwonEpilogue = 1;
                missionVariables.erehwonActiontime = clock.days + 30;
                player.ship.removeEquipment("EQ_EREHWON_PHOTOCAMERA");
                mission.setInstructionsKey(null);
                this.$unmarkSystem(124);
                player.credits += 500;
            }
            if (missionVariables.erehwonReconnaissance == "ACCEPTED" &&
                    missionVariables.erehwonPictureCount == 0 &&  missionVariables.erehwonFotoShot == "NO") {
                mission.runScreen({
					screenID:"tionisla_reporter",
                    titleKey: "tr_chronicle_title",
                    messageKey: "erehwonReconnaissance_failure",
                    choicesKey: "erehwonReconnaissance_choice2"
                    }, this.choiceEvaluation
                );
            }
            if (missionVariables.erehwonReconnaissance == "ACCEPTED" &&
                    player.ship.equipmentStatus("EQ_EREHWON_PHOTOCAMERA") == "EQUIPMENT_DAMAGED") {
                mission.runScreen({
					screenID:"tionisla_reporter",
                    titleKey: "tr_chronicle_title",
                    messageKey: "erehwonReconnaissance_damaged",
                    choicesKey: "erehwonReconnaissance_choice2"
                    }, this.choiceEvaluation
                );
            }
        }
        /*if (system.ID == 144 && missionVariables.erehwomMisJumpInfo !== "") {
            missionVariables.erehwomMisJumpInfo = "BIORLE";
        }
        if (system.ID == 48 && missionVariables.erehwomMisJumpInfo == "BIORLE") {
            missionVariables.erehwomMisJumpInfo = "USLE";
        }*/
        if (system.ID == 144 && missionVariables.erehwomMisJumpInfo !== "GIVEN") {
            mission.runScreen({
                titleKey: "tr_chronicle_title",
                messageKey: "erehwonReconnaissance_biorle"
            });
            missionVariables.erehwomMisJumpInfo = "GIVEN";
        }
        if (missionVariables.erehwonReconnaissance == "DECLINED" && missionVariables.erehwonActiontime > clock.days) {
            mission.runScreen({
				screenID:"tionisla_reporter",
                titleKey: "tr_chronicle_title",
                messageKey: "erehwonReconnaissance_declined"
            });
            missionVariables.erehwonReconnaissance = "FINISHED";
            missionVariables.erehwonTimerStart = null;
            this.cleanUp();
        }
        if (missionVariables.erehwonReconnaissance == "EPILOGUE" && clock.days > missionVariables.erehwonActiontime) {
            if (!missionVariables.erehwonDestroyed || missionVariables.erehwonDestroyed === false) {
                // credits for the idea and next 6 messages go to SandJ
                var erehwonEpilogue = missionVariables.erehwonEpilogue++;
                missionVariables.erehwonActiontime = clock.days + 30; // set new time
                mission.runScreen({
    				screenID:"tionisla_reporter",
                    titleKey: "tr_chronicle_title",
                    messageKey: "erehwonReconnaissance_epilogue_" + erehwonEpilogue
                });
                switch(erehwonEpilogue) {
                    case 1:
                        player.credits += 50;
                        break;
                    case 2:
                        player.ship.fuel = 7;
                        break;
                    case 3:
                        var narcotics = player.ship.cargoSpaceAvailable;
                        if (narcotics > 35) narcotics = 35; // add a limit
                        manifest.narcotics += narcotics;
                        break;
                    case 4:
                        player.credits += 75;
                        break;
                    case 5:
                        player.credits += 50;
                        missionVariables.erehwonActiontime += 100; // wait a bit longer for the last one
                        break;
                    case 6:
                        manifest.gem_stones += 100;
                    default:
                        // we ran out of messages. Clean up now.
                        missionVariables.erehwonActiontime = null;
                        missionVariables.erehwonEpilogue = null;
                        missionVariables.erehwonReconnaissance = "FINISHED";
                        this.cleanUp();
                        break;
                }
            }
        }
    } else if (player.ship.dockedStation.displayName == "Erehwon Station") {
        if (missionVariables.erehwonGotStory && missionVariables.erehwonGotStory == "NO") {
            missionVariables.erehwonGotStory = "YES";
            mission.runScreen({
                screenID:"tionisla_reporter",
                titleKey: "tr_chronicle_title",
                messageKey: "erehwonReconnaissance_story"
            });
        }
        if (missionVariables.erehwonFotoShot && missionVariables.erehwonFotoShot == "YES") {
            if (missionVariables.erehwonReconnaissance != "SUCCESS")
            {
                this.$unmarkSystem(144);
                this.$markSystem(124);
            }
            missionVariables.erehwonReconnaissance = "SUCCESS";
            mission.setInstructionsKey("erehwonReconnaissance_missioninfo2");
        }
    }
}

//-------------------------------------------------------------------------------------------------------------
this.choiceEvaluation = function (choice) {
    switch (choice) {
        case "OFFER_ACCEPTED":
            missionVariables.erehwonReconnaissance = "ACCEPTED";
            player.ship.awardEquipment("EQ_EREHWON_PHOTOCAMERA");
            missionVariables.erehwonPictureCount = 10;
            mission.setInstructionsKey("erehwonReconnaissance_missioninfo1");
            this.$markSystem(144);
            mission.runScreen({
				screenID:"tionisla_reporter",
                titleKey: "tr_chronicle_title",
                messageKey: "erehwonReconnaissance_accepted"
                }
            );
            break;

        case "OFFER_DECLINED":
            missionVariables.erehwonReconnaissance = "DECLINED";
            missionVariables.erehwonActiontime = clock.days + 30;
            break;
    }
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillEnterWitchspace = function (cause) {
	missionVariables.showErehwon = "NO"; // avoid adding planet on multiple misjumps.
    if (!system.isInterstellarSpace && galaxyNumber === 0) {
		if (cause === "standard jump" && (system.ID === 48 || system.ID === 144)) {
            missionVariables.showErehwon = "YES";
			if (missionVariables.erehwomMisJumpInfo == "GIVEN" && (system.ID == 48 || system.ID == 144) && cause === "standard jump") {
				if ((player.ship.targetSystem == 48 || player.ship.targetSystem == 144) && Math.random() < 0.2) {
					player.ship.scriptedMisjump = true;
				}
			}
		}
    }
}

//-------------------------------------------------------------------------------------------------------------
this.shipExitedWitchspace = function () {
    if (this._restoreIST === true) {
        worldScripts["IST_masterScript"].shipWillExitWitchspace = worldScripts["IST_masterScript"].$hold_shipWillExitWitchspace;
        delete worldScripts["IST_masterScript"].$hold_shipWillExitWitchspace;
        this._restoreIST = false;
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$markSystem = function (ID) {
    if (0 < oolite.compareVersion("1.77")) {
        mission.markSystem(ID);
    } else {
        mission.markSystem({
            system: ID,
            name: "Tionisla Reporter",
            markerColor: "magentaColor",
            markerShape: "MARKER_DIAMOND"
        });
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$unmarkSystem = function (ID) {
    if (0 < oolite.compareVersion("1.77")) {
        mission.unmarkSystem(ID);
    } else {
        var ok = mission.unmarkSystem({system: ID, name: "Tionisla Reporter"});
        if (!ok) mission.unmarkSystem(ID); // must have had a legacy marker. Clear that also.
    }
}

//-------------------------------------------------------------------------------------------------------------
this.cleanUp = function () {
    delete this.missionScreenOpportunity;
    //delete this.shipWillEnterWitchspace;
}

//-------------------------------------------------------------------------------------------------------------
this.$erehwon_systemWillPopulate = function() {
    if (this.$populatorRun) return;
    // turn off IST, just in case
    if (worldScripts["IST_masterScript"]) {
        worldScripts["IST_masterScript"].$hold_shipWillExitWitchspace = worldScripts["IST_masterScript"].shipWillExitWitchspace;
        delete worldScripts["IST_masterScript"].shipWillExitWitchspace;
        this._restoreIST = true;
    }

	system.setPopulator("oolite-interstellar-thargoids", {
        priority: 10,
        location: "WITCHPOINT",
        groupCount: 2 + Math.floor(Math.random() * 4),
        callback: function(pos) {system.addShips("thargoid", 1, pos, 0);}
	});
	this.$populatorRun = true;

	if (missionVariables.showErehwon === "YES") {
        system.addPlanet("Planet_Erehwon");
        // only add the station if it hasn't been destroyed
        if (!missionVariables.erehwonDestroyed || missionVariables.erehwonDestroyed === false) {
            system.addShips("erehwonStation", 1, Vector3D(-50000, 4000, 413000).fromCoordinateSystem("abs"), 1);
        }
	}
}
