"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, key, oldValue, newValue, layer);

this.$pendingChange = null;

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

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

    // Compare parameters with this.$pendingChange
    if (this.$pendingChange &&
        this.$pendingChange.galaxyID === galaxy &&
        this.$pendingChange.systemID === system &&
        this.$pendingChange.property === key &&
        this.$pendingChange.newValue === newValue) {
        // Match found: copy oldValue and layer from this.$pendingChange
        oldValue = this.$pendingChange.oldValue;
        layer = this.$pendingChange.layer;
        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:  " + key + "\n" +
                     "- Old value: " + oldValue + "\n" +
                     "- New value: " + newValue + "\n" +
                     "- Layer: " + layer;

    // 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: key,
        oldValue: oldValue,
        newValue: newValue,
        layer: layer,
        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
};