"use strict";

// worldScripts.sysInfoChangeLog

this.name = "sysInfoChangeLog";

// To enable an "undo" log to be maintained, before changing system information, call:
// worldScripts.sysInfoChangeLog._pendingChange(galaxy, system, property, oldValue, newValue, layer, owner);

this.$pendingChange = null;

this._pendingChange = function (galaxy, system, property, oldValue, newValue, layer, owner) {
    if (typeof owner === "undefined") {
        owner = this.name;
    }
    if (typeof layer === "undefined") {
        layer = 2;
    }
    this.$pendingChange = {
        galaxyID: galaxy,
        systemID: system,
        property: property,
        oldValue: oldValue,
        newValue: newValue,
        layer: layer,
        owner: owner
    };
};

this.systemInformationChanged = function (galaxy, system, property, newValue) {
    // Initialize variables for oldValue, owner and layer
    var oldValue = "UNKNOWN";
    var layer = "UNKNOWN";
    var owner = "UNKNOWN";

    // Compare parameters with this.$pendingChange
    if (this.$pendingChange &&
        this.$pendingChange.galaxyID === galaxy &&
        this.$pendingChange.systemID === system &&
        this.$pendingChange.property === property &&
        this.$pendingChange.newValue === newValue) {
        // Match found: copy oldValue, owner and layer from this.$pendingChange
        oldValue = this.$pendingChange.oldValue;
        layer = this.$pendingChange.layer;
        owner = this.$pendingChange.owner;
        this.$pendingChange = null; // Clear the pending change
    }

    // Log the change to the console or a mission log
    var logMessage = "System information changed:\n" +
                     "- Galaxy ID: " + galaxy + "\n" +
                     "- System ID: " + system + "\n" +
                     "- Property:  " + property + "\n" +
                     "- Old value: " + oldValue + "\n" +
                     "- New value: " + newValue + "\n" +
                     "- Layer: " + layer + "\n" +
                     "- Owner: " + owner;

    // Log the change to the Oolite log file
    log(this.name, logMessage);

    // Store the change in a mission variable for later reference
    if (!missionVariables.World_Builder_systemChangeLog) {
        missionVariables.World_Builder_systemChangeLog = []; // Initialize as an empty array if not already set
    }
    var changeLog = JSON.parse(missionVariables.World_Builder_systemChangeLog || "[]");
    changeLog.push({
        galaxyID: galaxy,
        systemID: system,
        property: property,
        oldValue: oldValue,
        newValue: newValue,
        layer: layer,
        owner: owner,
        timestamp: clock.seconds // Log the time of the change
    });
    if (changeLog.length > 100) { // Keep only the last 100 changes
        changeLog.shift(); // Remove the oldest entry
    }
    missionVariables.World_Builder_systemChangeLog = JSON.stringify(changeLog); // Save back to mission variables

    // Avoid recursion by not modifying system properties here
    // Any attempt to do so will fail and log an error
};


/* ========================================================
        UNDO FUNCTIONALITY
=========================================================== */

this._undoLastChange = function () {
    // Retrieve the change log
    if (!missionVariables.World_Builder_systemChangeLog) {
        mission.runScreen({
            title: "World Builder",
            message: "No changes to undo.",
            exitScreen: "GUI_SCREEN_SYSTEM_DATA",
            allowInterrupt: true,
            screenID: "world_builder"
        });
        return;
    }

    var changeLog = JSON.parse(missionVariables.World_Builder_systemChangeLog);
    if (changeLog.length === 0) {
        mission.runScreen({
            title: "World Builder",
            message: "No changes to undo.",
            exitScreen: "GUI_SCREEN_SYSTEM_DATA",
            allowInterrupt: true,
            screenID: "world_builder"
        });
        return;
    }

    // Get the most recent change
    const lastChange = changeLog.pop(); // Remove the last change from the log
    const { galaxyID, systemID, property, oldValue } = lastChange;

    // Revert the change
    const sys = System.infoForSystem(galaxyID, systemID);
    if (sys[property] !== undefined) {
        sys[property] = oldValue; // Revert the property to its old value

        // Save the updated log back to mission variables
        missionVariables.World_Builder_systemChangeLog = JSON.stringify(changeLog);

        // Notify the user
        mission.runScreen({
            title: "World Builder",
            message: "Undid the last change:\n" +
                     "- Property: " + property + "\n" +
                     "- Old Value: " + oldValue,
            exitScreen: "GUI_SCREEN_SYSTEM_DATA",
            allowInterrupt: true,
            screenID: "world_builder"
        });
    } else {
        mission.runScreen({
            title: "World Builder",
            message: "Failed to undo the last change. The property may no longer exist.",
            exitScreen: "GUI_SCREEN_SYSTEM_DATA",
            allowInterrupt: true,
            screenID: "world_builder"
        });
    }
};

/* ========================================================
        ADD UNDO OPTION TO THE INTERFACES
=========================================================== */
/*
this._applyInterface = function () {
    if (system.mainStation) {
        system.mainStation.setInterface("world_builder_undo", {
            title: "World Builder (undo last change)",
            category: expandDescription("[interfaces-category-uncategorised]"),
            summary: "Undo the last change made to system information by World Builder.",
            callback: this._undoLastChange.bind(this)
        });
    }
};
*/
/* ========================================================
		THE END
=========================================================== */