"use strict";
this.name = "FuelTweaks_Quirium";
this.author = "phkb";
this.copyright = "2017 phkb";
this.description = "Routines for controlling the collection, sale and transport of scooped Quirium fuel";
this.licence = "CC BY-NC-SA 4.0";

/*
    TODO:
        firing on, or using ecm near, to a cargo pod with Quirium inside will result in a cascade explosion
*/

this._scoopDistanceTimer = null;
this._damagedStorage = 0;
this._preProcessAmount = 0;
this._scoopProcess = 0;
this._fuelScoopStorage = false;
this._chs = false;
this._mo_timer = null;
this._purchase = {};
this._minAmount = 0.1;
this._shipConfig = false;
this._scEquip = [];
this._itemColor = "yellowColor";
this._menuColor = "orangeColor";
this._exitColor = "yellowColor";
this._disabledColor = "darkGrayColor";
this._startCount = 0;
this._secondTimer = null;
this._transferTimer = null;
this._destructTimer = null;
this._damageChance = 0.02; // 0.05 0.1;
this._destructCounter = 0;
this._destructPhase = 0;
this._oneTAmount = 7;                       /// amount of scooped fuel that will be considered "1t"
//this._dumpQuirium = null;

//-------------------------------------------------------------------------------------------------------------
this.startUpComplete = function () {
    if (missionVariables.FuelTweaks_PreProcessAmount) this._preProcessAmount = missionVariables.FuelTweaks_PreProcessAmount;
    if (missionVariables.FuelTweaks_ScoopProcess) this._scoopProcess = missionVariables.FuelTweaks_ScoopProcess;
    if (worldScripts["Coronal Harvester Script"]) this._chs = true;
    if (worldScripts.ShipConfiguration_Core) {
        this._shipConfig = true;
    }
    if (worldScripts["Fuel Collector"]) {
        worldScripts["Fuel Collector"].$CruiseCheck = this.$fuelCollector_CruiseCheck;
        worldScripts["Fuel Collector"].$checkifover01 = this.$fuelCollector_checkifover01;
    }
    this.$initInterface(player.ship.dockedStation);
}

//-------------------------------------------------------------------------------------------------------------
this.shipLaunchedFromStation = function (station) {
    if (player.ship.equipmentStatus("EQ_FUEL_PROCESSOR") === "EQUIPMENT_OK") {
        this._scoopDistanceTimer = new Timer(this, this.$monitorPlayer, 5, 5);
    }
    if (this._shipConfig === true) {
        var sc = worldScripts.ShipConfiguration_Core;
        var eq = EquipmentInfo.infoForKey(sc.$equipmentItemInUse("fuelscoops", player.ship));
        if (eq) this._minAmount = parseFloat(eq.scriptInfo.accumulator_size) + 0.1;
        // grab a copy of sc equipment that will report itself as damaged, so we don't double up during a self-destruct
        this._scEquip = [].concat(sc._engines).concat(sc._boosters).concat(sc._hyperdrive).concat(sc._thrusters)
            .concat(sc._energy).concat(sc._frontshields).concat(sc._aftshields).concat(sc._fuelinjectors)
            .concat(sc._fuelscoops).concat(sc._heatshields);
    }
}

//-------------------------------------------------------------------------------------------------------------
this.playerWillSaveGame = function () {
    missionVariables.FuelTweaks_PreProcessAmount = this._preProcessAmount;
    missionVariables.FuelTweaks_ScoopProcess = this._scoopProcess;
}

//-------------------------------------------------------------------------------------------------------------
this.shipDied = function (whom, why) {
    if (this._scoopDistanceTimer && this._scoopDistanceTimer.isRunning) this._scoopDistanceTimer.stop();
    this._scoopDistanceTimer = null;
    this.$stopTimers();
}

//-------------------------------------------------------------------------------------------------------------
this.shipDockedWithStation = function (station) {
    if (this._scoopDistanceTimer && this._scoopDistanceTimer.isRunning) this._scoopDistanceTimer.stop();
    this._scoopDistanceTimer = null;
    this.$initInterface(station);
    this.$stopTimers();
}

//-------------------------------------------------------------------------------------------------------------
this.equipmentDamaged = function (equipmentKey) {
    // if a full storage container gets damaged, remove a fuel commodity from the player
    if (equipmentKey === "EQ_FUEL_PROCESSOR" || equipmentKey === "EQ_FUEL_STORAGE") {
        var curr = player.ship.manifest["quirium_fuel"];
        var cntr = this.$countOKContainers();
        if (curr > cntr) {
            player.ship.manifest["quirium_fuel"] -= (curr - cntr);
        }
    }
}

//-------------------------------------------------------------------------------------------------------------
this.playerBoughtEquipment = function (equipmentKey) {
    var p = player.ship;
    var refundEq = "";
    if (equipmentKey === "EQ_FUEL_STORAGE_REMOVAL") {
        p.removeEquipment("EQ_FUEL_STORAGE_REMOVAL");
        refundEq = "EQ_FUEL_STORAGE";
    }
    if (equipmentKey === "EQ_FUEL_PROCESSOR_REMOVAL") {
        p.removeEquipment("EQ_FUEL_PROCESSOR_REMOVAL");
        refundEq = "EQ_FUEL_PROCESSOR";
        mission.setInstructions("", this.name);
    }
    if (equipmentKey === "EQ_FUEL_TRANSFER_REMOVAL") {
        p.removeEquipment("EQ_FUEL_TRANSFER_REMOVAL");
        refundEq = "EQ_FUEL_TRANSFER";
    }
    if (equipmentKey === "EQ_FUEL_STORAGE") {
        if (p.equipmentStatus("EQ_FUEL_STORAGE", true)["EQUIPMENT_DAMAGED"] > 0) {
            p.setEquipmentStatus("EQ_FUEL_STORAGE", "EQUIPMENT_OK");
            p.removeEquipment("EQ_FUEL_STORAGE");
        }
    }
    if (equipmentKey === "EQ_FUEL_PROCESSOR") {
        this._preProcessAmount = 0;
        this.$updateManifest();
    }
    if (refundEq !== "") {
        var stn = p.dockedStation;
        var eqSts = p.equipmentStatus(refundEq);
        p.removeEquipment(refundEq);
        var eq = EquipmentInfo.infoForKey(refundEq);
        // refund the cost of the equipment
        if (eqSts === "EQUIPMENT_OK") player.credits += (eq.price / 10) * stn.equipmentPriceFactor;
        if (eqSts === "EQUIPMENT_DAMAGED") player.credits += ((eq.price / 10) * stn.equipmentPriceFactor) / 2;
    }
    if (equipmentKey === "EQ_FUEL_TRANSFER" || equipmentKey === "EQ_FUEL_TRANSFER_REMOVAL") {
        this.$initInterface(player.ship.dockedStation);
    }
}

//-------------------------------------------------------------------------------------------------------------
this.playerBoughtCargo = function (commodity, units, price) {
    if (commodity === "quirium_fuel") {
        var spare = this.$countOKContainers() - player.ship.manifest["quirium_fuel"];
        if (spare < 0) {
            player.consoleMessage(expandMissionText("FT_quirium_unable"), 5);
            player.ship.manifest["quirium_fuel"] -= Math.abs(spare);
            player.ship.dockedStation.setMarketQuantity(commodity, player.ship.dockedStation.market[commodity].quantity + Math.abs(spare));
            player.credits += (Math.abs(spare) * (price / 10));
            if (worldScripts.market_observer3) {
                this._mo_timer = new Timer(this, this.$reverseMOPurchase, 0.5, 0);
                this._purchase = { commodity: commodity, units: units, price: price };
            }
            return;
        }
    }
}

//-------------------------------------------------------------------------------------------------------------
this.shipLaunchedEscapePod = function (escapepod) {
    this.$stopTimers();
}

//-------------------------------------------------------------------------------------------------------------
this.shipScoopedFuel = function () {
    if (this._fuelScoopStorage === true) {
        // send this fuel to storage
        this._preProcessAmount += this._minAmount;
        this.$updateManifest();
        // display some status info ... somewhere ...
        var checkCalc = parseInt(Math.abs(parseFloat(this._preProcessAmount) - parseFloat(this._oneTAmount) * ((this._scoopProcess + 1) * 0.25)) * 100);
        var p = player.ship;
        if (this._scoopProcess === 2 && checkCalc <= 5) {
            player.consoleMessage(expandMissionText("FT_quirium_scoop", { amount: "75%" }), 5);
            this._scoopProcess += 1;
        }
        if (this._scoopProcess === 1 && checkCalc <= 5) {
            player.consoleMessage(expandMissionText("FT_quirium_scoop", { amount: "50%" }), 5);
            this._scoopProcess += 1;
        }
        if (this._scoopProcess === 0 && checkCalc <= 5) {
            player.consoleMessage(expandMissionText("FT_quirium_scoop", { amount: "25%" }), 5);
            this._scoopProcess += 1;
        }
        if (this._preProcessAmount >= this._oneTAmount) {
            p.manifest["quirium_fuel"] += 1;
            this._preProcessAmount = 0;
            this._scoopProcess = 0;
            this.$updateManifest();
            player.consoleMessage(expandMissionText("FT_quirium_processed"), 5);
            // add an extra blank line otherwise the "Fuel scoop active" message will overwrite it
            var curr = p.manifest["quirium_fuel"];
            var cntr = this.$countOKContainers();
            if (curr === cntr) {
                this._fuelScoopStorage = false;
                player.consoleMessage(expandMissionText("FT_quirium_halted"), 5);
                return;
            }
            if (p.cargoSpaceAvailable === 0) {
                this._fuelScoopStorage = false;
                player.consoleMessage(expandMissionText("FT_quirium_capacity"), 5);
                return;
            }
        }
        // subtract the amount from the player's fuel so 
        p.fuel -= this._minAmount;
    }
}

//-------------------------------------------------------------------------------------------------------------
this.shipScoopedOther = function (whom) {
    if (whom.isCargo && whom.commodity === "quirium_fuel") {
        // we automatically gain an qfsu whenever we scoop quirium fuel
        var p = player.ship;
        p.awardEquipment("EQ_FUEL_STORAGE");
        /*var curr = p.manifest["quirium_fuel"];
        var cntr = this.$countOKContainers();
        if (curr > cntr) {
            // if we don't have any quirium on board, but we do have a processor, we don't need to add a separate fuel storage unit
            if (curr === 0 && player.ship.equipmentStatus("EQ_FUEL_PROCESSOR") === "EQUIPMENT_OK") return;
            var diff = curr - cntr;
            //this._dumpQuirium = new Timer(this, this.$dumpQuirium, 1, 0);
            // player picks up fuel storage unit with the fuel if they don't have enough of them 
            for (var i = 0; i < diff; i++) {
                p.awardEquipment("EQ_FUEL_STORAGE");
            }
        }*/
    }
}

//-------------------------------------------------------------------------------------------------------------
this.shipDumpedCargo = function (cargo) {
    if (cargo.commodity === "quirium_fuel") {
        // if we just dumped quirium, we dumped the storage unit with it.
        var result = player.ship.removeEquipment("EQ_FUEL_STORAGE");
    }
}

//-------------------------------------------------------------------------------------------------------------
// not used any more, but kept just in case
/*this.$dumpQuirium = function $dumpQuirium() {
    player.consoleMessage("Unable to store Quirium Fuel safely - auto-ejecting cargo!", 5);
    // hopefully this will dump the just-scooped entity
    player.ship.dumpCargo(1, "quirium_fuel");
}*/

//-------------------------------------------------------------------------------------------------------------
// start the process (after second press)
this.activated = function () {
    if (player.ship.fuel === 7) {
        player.consoleMessage(expandMissionText("FT_quirium_full"));
        return;
    }
    if (player.ship.manifest["quirium_fuel"] === 0) {
        player.consoleMessage(expandMissionText("FT_quirium_nostorage"));
        return;
    }
    var ft = worldScripts.FuelTweaks_Quirium;
    // stop the process, if it's running
    if (ft._transferTimer && ft._transferTimer.isRunning) { ft.mode(); return; }
    // ask the player again before starting
    if (this._startCount === 0) {
        this._startCount = 1;
        ft._secondTimer = new Timer(ft, ft.$cancelStart, 20, 0);
        player.consoleMessage(expandMissionText("FT_quirium_activateagain"));
        return;
    }
    // ok we're really starting now
    if (this._startCount === 1) {
        this._startCount = 0;
        if (ft._secondTimer.isRunning) ft._secondTimer.stop();
        ft._transferTimer = new Timer(ft, ft.$doFuelTransfer, 2, 2);
        player.consoleMessage(expandMissionText("FT_quirium_tfrstarted"), 2);
    }
}

//-------------------------------------------------------------------------------------------------------------
// stop process
this.mode = function () {
    var ft = worldScripts.FuelTweaks_Quirium;
    if (ft._transferTimer && ft._transferTimer.isRunning) {
        player.ship.manifest["quirium_fuel"] -= 1;
        ft._damageChance = 0.02;
        ft._transferTimer.stop();
        player.consoleMessage(expandMissionText("FT_quirium_tfrstopped"));
    }
}

//-------------------------------------------------------------------------------------------------------------
this.playerStartedJumpCountdown = this.shipWillEnterWitchspace = function () {
    // starting a witchspace jump, or entering a wormhole, should now automatically stop any transfer in progress
    this.mode();
}

//-------------------------------------------------------------------------------------------------------------
this.$cancelStart = function $cancelStart() {
    this._startCount = 0;
}

//-------------------------------------------------------------------------------------------------------------
this.$doFuelTransfer = function $doFuelTransfer() {
    var p = player.ship;
    if (p.equipmentStatus("EQ_FUEL_TRANSFER") === "EQUIPMENT_DAMAGED") {
        this.mode();
        return;
    }
    p.fuel += 0.1;
    if (p.fuel >= 7) {
        p.fuel = 7;
        player.consoleMessage(expandMissionText("FT_quirium_complete"));
        this.mode();
        return;
    }
    player.consoleMessage("Fuel transfer in progress", 1.5);
    // will there be damage?
    if (Math.random() < this._damageChance) {
        // yes there is
        // but what type?
        var type = Math.random();
        if (type >= 0 && type < 0.76) {
            // cargo - grab a copy of the array
            var c = p.manifest.list.splice(0);
            // sort it randomly
            c.sort(function (a, b) { return Math.random() - 0.5; });
            var amt = 0;
            var cmdty = "";
            var unit = "t";
            for (var i = 0; i < c.length; i++) {
                if (c[i].quantity > 0 && c[i].unit === "t") {
                    amt = 1;
                    cmdty = c[i].commodity;
                    p.manifest[c[i].commodity] -= 1;
                    break;
                }
                if (c[i].quantity > 0 && c[i].unit !== "t") {
                    amt = Math.floor(Math.random() * c[i].quantity) + 1;
                    cmdty = c[i].commodity;
                    unit = c[i].unit;
                    p.manifest[c[i].commodity] -= amt;
                    break;
                }
            }
            if (cmdty != "") {
                player.consoleMessage(expandMissionText("FT_quirium_warning", { amount: amt, unit: unit, commodity: displayNameForCommodity(cmdty) }));
                var mySound = new SoundSource;
                mySound.sound = "[player-scrape-damage]";
                mySound.loop = false;
                mySound.play();
                // check to see if we've destroyed all the stored quirium fuel 
                if (cmdty === "quirium_fuel" && p.manifest[cmdty] === 0) {
                    this._damageChance = 0.02;
                    this._transferTimer.stop();
                    player.consoleMessage(expandMissionText("FT_quirium_insufficient"));
                }
            } else {
                // theoretically this can never happen - if there's no cargo to destroy, then there's
                // no quirium fuel left, so the process should have been stopped in the clause above
                type = 0.6; // switch to equipment damage if no cargo available
            }
        }
        if (type >= 0.76 && type < 0.9995) {
            // equipment
            this.$performEquipmentDamage();
        }
        if (type >= 0.9995) {
            this._transferTimer.stop();
            p.script._findMe = true;
            // oh dear - the ship!
            player.consoleMessage(expandMissionText("FT_quirium_failure"));
            // start the self-destruct sequence
            this._destructPhase = 0;
            this._destructTimer = new Timer(this, this.$destructSequence, 2, 2);
            // slowly damage every equipment item
            // turn off hud and replace with custom one that only has console at top left corner
            // show a brief series of error messages then either (a) eject the player or (b) destroy their ship.
        }
    }
    this._damageChance += 0.01; // slowly increate the damage chance.
}

this.$testDestruct = function () {
    // oh dear - the ship!
    player.consoleMessage(expandMissionText("FT_quirium_failure"));
    // start the self-destruct sequence
    this._destructPhase = 0;
    this._destructTimer = new Timer(this, this.$destructSequence, 2, 2);
}

//-------------------------------------------------------------------------------------------------------------
this.$destructSequence = function $destructSequence() {
    this.$performEquipmentDamage();
    this._destructCounter += 1;
    if (this._destructCounter > 8) {
        // switch off hud
        this._storeHUD = player.ship.hud;
        player.ship.hud = "destruct_hud.plist";
        // unbreak the breakable IFF scanner (if present and damaged) so the final sequence display is shown clearly
        if (player.ship.equipmentStatus("EQ_BREAKABLE_HUD_IFF_SCANNER") === "EQUIPMENT_DAMAGED") player.ship.setEquipmentStatus("EQ_BREAKABLE_HUD_IFF_SCANNER", "EQUIPMENT_OK");
        this._destructPhase = 1;
        this._destructTimer.stop();
        this._destructCounter = 0;
        this._destructTimer = new Timer(this, $destructFinalSequence, 1, 1);
    }
}

//-------------------------------------------------------------------------------------------------------------
// we're doing this manually, rather than using takeInternalDamage, so we can (a) exclude some items, and (b) only damage equipment
this.$performEquipmentDamage = function () {
    // list of equipment items we don't want to damage (either because they're critical to gameplay, or it just doesn't make sense)
    var noDamage = ["EQ_HULL_REPAIR"];
    var p = player.ship;

    // grab a copy of the equipment list
    var eq = p.equipment.slice(0);
    // randomly sort the list
    eq.sort(function (a, b) { return Math.random() - 0.5; });
    for (var i = 0; i < eq.length; i++) {
        var eqItem = eq[i];
        // find an item to damage (but not the escape pod)
        if (noDamage.indexOf(eqItem.equipmentKey) === -1 && eqItem.provides.indexOf("EQ_ESCAPE_POD") === -1 && p.equipmentStatus(eqItem.equipmentKey) == "EQUIPMENT_OK" && eqItem.damageProbability != 0 && eqItem.isVisible == true && Math.random() <= eqItem.damageProbability) {
            p.setEquipmentStatus(eqItem.equipmentKey, "EQUIPMENT_DAMAGED");
            if (this._scEquip.indexOf(eqItem.equipmentKey) === -1) {
                player.consoleMessage(expandMissionText("FT_quirium_damage", { equipment: eqItem.name }));
            }
            var mySound = new SoundSource;
            mySound.sound = "[player-scrape-damage]";
            mySound.loop = false;
            mySound.play();
            break;
        }
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$destructFinalSequence = function $destructFinalSequence() {
    var msg = [
        "",
        expandMissionText("FT_destruct_seq_1"),
        expandMissionText("FT_destruct_seq_2"),
        expandMissionText("FT_destruct_seq_3"),
        expandMissionText("FT_destruct_seq_4"),
        expandMissionText("FT_destruct_seq_5"),
        expandMissionText("FT_destruct_seq_6")
    ];
    this._destructCounter += 1;
    if (this._destructCounter < msg.length) {
        player.consoleMessage(msg[this._destructCounter]);
        return;
    }
    if (this._destructCounter >= msg.length) {
        if (this._destructPhase === 1) this._destructPhase = 2;
        if (this._destructPhase === 2 && player.ship.hasEquipmentProviding("EQ_ESCAPE_POD") === "EQUIPMENT_OK") {
            player.consoleMessage(expandMissionText("FT_destruct_autoeject"));
            player.ship.throwSpark();
            this._destructPhase = 3;
            player.ship.abandonShip();
            return;
        }
        this._destructTimer.stop();
        this._explodeTimer = new Timer(this, this.$explodeShip, 0.25, 0);
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$explodeShip = function $explodeShip() {
    this.$stopTimers();
    player.ship.explode();
    player.ship.hud = this._storeHUD;
}

//-------------------------------------------------------------------------------------------------------------
this.$stopTimers = function () {
    if (this._secondTimer && this._secondTimer.isRunning) this._secondTimer.stop();
    if (this._transferTimer && this._transferTimer.isRunning) this.mode();
    if (this._scoopDistanceTimer && this._scoopDistanceTimer.isRunning) this._scoopDistanceTimer.stop();
    if (this._destructTimer && this._destructTimer.isRunning) this._destructTimer.stop();
    //if (this._dumpQuirium && this._dumpQuirium.isRunning) this._dumpQuirium.stop();
}

//-------------------------------------------------------------------------------------------------------------
// initialise the F4 screen entries
this.$initInterface = function (station) {
    if (player.ship.equipmentStatus("EQ_FUEL_TRANSFER") === "EQUIPMENT_OK") {
        station.setInterface(this.name, {
            title: expandMissionText("FT_quirium_title"),
            category: expandDescription("[interfaces-category-ship-systems]"),
            summary: expandMissionText("FT_quirium_summary"),
            callback: this.$showScreen.bind(this)
        });
    } else {
        station.setInterface(this.name, null);
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$showScreen = function () {
    var text = "";
    if (player.ship.manifest["quirium_fuel"] === 0 || player.ship.fuel === 7) {
        text = expandMissionText("FT_quirium_noneavail");
        if (player.ship.fuel === 7) text = expandMissionText("FT_quirium_notrequired");
        mission.runScreen({
            screenID: "oolite-quirium-fuel-map",
            title: expandMissionText("FT_quirium_title"),
            overlay: { name: "fuelTweaks_pump.png", height: 546 },
            message: text,
            exitScreen: "GUI_SCREEN_INTERFACES"
        });
    } else {
        text = expandMissionText("FT_quirium_confirm", { amount: (7 - player.ship.fuel) });
        var curChoices = {};
        curChoices["01_YES"] = { text: expandMissionText("FT_quirium_proceed"), color: this._menuColor };
        curChoices["02_NO"] = { text: expandMissionText("FT_quirium_return"), color: this._menuColor };

        var opts = {
            screenID: "oolite-quirium-transfer-map",
            title: expandMissionText("FT_quirium_confirm_title"),
            overlay: { name: "fuelTweaks_pump.png", height: 546 },
            allowInterrupt: true,
            exitScreen: "GUI_SCREEN_INTERFACES",
            choices: curChoices,
            initialChoicesKey: "02_NO",
            message: text
        };
        mission.runScreen(opts, this.$screenHandler, this);
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$screenHandler = function (choice) {
    if (!choice) return;
    if (choice === "01_YES") {
        var amt = 7 - player.ship.fuel;
        player.ship.fuel = 7;
        player.ship.manifest["quirium_fuel"] -= 1;
        player.consoleMessage(expandMissionText("FT_quirium_result", { amount: amt }));
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$reverseMOPurchase = function () {
    var mo = worldScripts.market_observer3;
    mo.playerSoldCargo(this._purchase.commodity, this._purchase.units, this._purchase.price);
    this._purchase = {};
}

//-------------------------------------------------------------------------------------------------------------
this.$monitorPlayer = function $monitorPlayer() {
    var p = player.ship;
    if (this.$playerWithinFuelScoopRange() === true) {
        // if it's already on, don't start it again
        if (this._fuelScoopStorage === true) return;
        // stay out of the way of the coronal harvester
        if (this._chs) {
            var chs = worldScripts["Coronal Harvester Script"];
            if (chs._vicinitySunTimer && chs._vicinitySunTimer.isRunning) return;
        }
        // do we have a processor?
        if (p.equipmentStatus("EQ_FUEL_PROCESSOR") === "EQUIPMENT_OK") {
            // how much space do we have?
            var curr = p.manifest["quirium_fuel"];
            var cntr = this.$countOKContainers();
            // if we have spare containers, and our fuel tanks are full, we can turn on the storage process
            if (curr < cntr && p.fuel >= 7 && p.cargoSpaceAvailable > 0) {
                // we have free space
                // enable some scooping action
                this._fuelScoopStorage = true;
                p.fuel -= this._minAmount;
            }
        }
    } else {
        // if the fuel process was active, and we're about to turn it off, make sure we give the player their fuel back.
        if (this._fuelScoopStorage === true) player.ship.fuel = 7;
        this._fuelScoopStorage = false;
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$playerWithinFuelScoopRange = function () {
    if (!system.sun) return false;
    if (((system.sun.collisionRadius * system.sun.collisionRadius) / system.sun.position.squaredDistanceTo(player.ship.position)) > 0.75) return true;
    return false;
}

//-------------------------------------------------------------------------------------------------------------
// returns the number of fuel containers
this.$countFuelContainers = function () {
    var fc = 0;
    var eq = player.ship.equipment;
    for (var i = 0; i < eq.length; i++) {
        if (eq[i].equipmentKey === "EQ_FUEL_STORAGE") fc += 1;
    }
    return fc;
}

//-------------------------------------------------------------------------------------------------------------
this.$countOKContainers = function () {
    if (player.ship && player.ship.equipmentStatus("EQ_FUEL_STORAGE", true) != undefined) {
        return player.ship.equipmentStatus("EQ_FUEL_STORAGE", true)["EQUIPMENT_OK"] + (player.ship.equipmentStatus("EQ_FUEL_PROCESSOR") === "EQUIPMENT_OK" ? 1 : 0);
    } else {
        return 0;
    }
}

//-------------------------------------------------------------------------------------------------------------
// fuel collector function overrides to enable fuel collection interface
this.$fuelCollector_checkifover01 = function (fuel_award) {
    this.fuel_below01 += fuel_award;
    var ftq = worldScripts.FuelTweaks_Quirium;
    if (this.fuel_below01 > 1000) {
        // only do something if we're /not/ in fuel scoop range of the sun
        // when we're in scoop range of the sun, the fuel scoop itself will take over
        if (ftq.$playerWithinFuelScoopRange() === false) {
            // if we have full fuel, pass the quirium over to the quirium fuel accumulator
            if (player.ship.fuel === 7) {
                var curr = player.ship.manifest["quirium_fuel"];
                var cntr = ftq.$countOKContainers();
                // are we in fuel scooping range?
                if (ftq._fuelScoopStorage === false && curr < cntr) {
                    ftq._fuelScoopStorage = true;
                    player.consoleMessage(expandMissionText("FT_fuelcollector_quirium"), 10);
                    player.consoleMessage(expandMissionText("FT_gathered"), 10);
                    ftq.shipScoopedFuel();
                    player.ship.fuel = 7;
                    ftq._fuelScoopStorage = false;
                }
            } else if (player.ship.fuel < 7) {
                // otherwise, it's just the normal fuel collector process here.
                player.ship.fuel += 0.1;
                player.consoleMessage(expandMissionText("FT_fuelcollector"), 10);
                player.consoleMessage(expandMissionText("FT_gathered"), 10);
            }
        }
        this.fuel_below01 -= 1000;
    }
}

//-------------------------------------------------------------------------------------------------------------
this.$fuelCollector_CruiseCheck = function () {
    if (player.ship.docked) {
        this.CruiseCheckTimer.stop()
        return // return because we really dont need more checking from here
        //return also saves a few cycles, instead of having the CPU do 3 extra Compares it just jumps to an address in memory
    }

    //if(this.tonearplanet) //if it is zero, then return
    //return

    // we never got here if the fuel collector was not started in the first place which is why
    // we can use explicit OR	
    if (player.ship.equipmentStatus("EQ_FRAME_FUEL_COLLECTOR") != "EQUIPMENT_OK" || player.ship.equipmentStatus("EQ_FUEL_SCOOPS") != "EQUIPMENT_OK") { //is EQ damaged ?
        this.CruiseCheckTimer.stop() // should we stop or keep it running, in order for it to be repaired..
        //i'd say performance is of the essense here, therefore we kill it until next witchspace / station launch
        return // return because we really dont need more checking from here
    }

    //player.ship.consoleMessage("entering cruisecheck", 3) // for testing


    //if(system.isInterstellarSpace) //some person in the future might add a sun in interstellar space
    if (!system.sun) {
        //so if there is a sun present, it will activate the crusing mode collector	
        if (this.ispaceswitch && this.firstrun) {
            this.ispaceswitch = false
            this.firstrun = false
            player.consoleMessage(expandMissionText("FT_fuelcollector"), 3)
            player.consoleMessage(expandMissionText("FT_interstellar_maxspeed"), 3)
        }

        //if there is not a sun there it will extract whatever it can from its surroundings..
        //however only as long as the player is at max speed.
        if (player.ship.speed == player.ship.maxSpeed)
            this.$checkifover01(this.fuel_level_1 * Math.random())
        return
    } else {
        //what distance are we at to the star
        // to close and it will shutdown, to far away it will collect very little

        /* a notice on why it shuts down, when to close
    	
        due to the fine filter of the fuel collector, it will shut down when it
        gets to close to the star so that the filter is having a chance of getting
        cleaned by the subsequent cleaning, which in effect harvest the fuel from
        the filter
    	
        The fuel scoop will then take over shortly after..
        */


        let sun_distance = player.ship.position.distanceTo(system.sun) + system.sun.radius
        /* This is the old shut off if to close to sun..
        // this however didnt take into consideration, the proximity to the planet
        */

        if ((player.ship.speed > player.ship.maxSpeed) || (7 == player.ship.fuel && !worldScripts.FuelTweaks_Quirium)) {//|| means explicit or // injector or warp speed
            return // return because we really dont need more checking from here
        }

        let distancemodifier = 10

        if (sun_distance < this.averagesun)
            distancemodifier = 30
        if (sun_distance < this.nearsun)
            distancemodifier = 50 //this is near the filters saturation limit,..

        let speedp = 100 / player.ship.maxSpeed * player.ship.speed

        if (speedp > 89) {
            this.$checkifover01(this.fuel_level_4 + distancemodifier)
            //player.consoleMessage("speed over 89 %", 3) // for testing
            return
        }

        if (speedp > 49) {
            this.$checkifover01(this.fuel_level_3 + distancemodifier)
            //player.consoleMessage("speed over 49 %",3) // for testing
            return
        }

        if (speedp > 19) {
            this.$checkifover01(this.fuel_level_2 + distancemodifier)
            //player.consoleMessage("speed over 19 %",3) // for testing
            return
        }
    }
}

this.$updateManifest = function $updateManifest() {
    mission.setInstructions(expandMissionText("FT_quirium_instructions", {status: (parseFloat(this._preProcessAmount / this._oneTAmount) * 100).toFixed(1)}), this.name);
}