var ahtFunctions = {

  savedPolicy: {},
  block: false,
  tabId: 0,

  startup: function() {
    consoleDebug("AHT: startup");

    // a block to really reset the settings only once, 
    // to prevent mixed up prefs
    ahtFunctions.block = false;
    // variable for the tab.id the reload listener is related to
    ahtFunctions.tabId = 0;
  },

  listenerToRestoreOriginalPrefs: function(tab) {
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: listenerToRestoreOriginalPrefs");
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: ahtFunctions.block = " + ahtFunctions.block);
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: previous saved tabId = " + ahtFunctions.tabId);
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: tab.id: " + tab.id);
    if ((ahtFunctions.block === true) && (ahtFunctions.tabId === tab.id)) {
      // Revert to the users default settings
      // after the message is reloaded.
      ahtFunctions.RestoreHTMLcontentPrefs();
    }
  },

  registerListener: function() {
    consoleDebug("AHT: registerListener listenerToRestoreOriginalPrefs");
    messenger.messageDisplay.onMessageDisplayed.addListener(ahtFunctions.listenerToRestoreOriginalPrefs);
  },

  removeListener: function() {
    consoleDebug("AHT: removeListener listenerToRestoreOriginalPrefs");
    messenger.messageDisplay.onMessageDisplayed.removeListener(ahtFunctions.listenerToRestoreOriginalPrefs);
  },

  allowHtmlTemp: async function(tabId, infoModifiers, remoteButton) {
    consoleDebug("AHT: allowHtmlTemp: fired");
    consoleDebug("AHT: allowHtmlTemp: options.debug = " + options.debug);
    consoleDebug("AHT: allowHtmlTemp: options.buttonHtmlMode = " + options.buttonHtmlMode);
    consoleDebug("AHT: allowHtmlTemp: options.tempRemoteContent = " + options.tempRemoteContent);
    consoleDebug("AHT: allowHtmlTemp: tabId: " + tabId);
    consoleDebug("AHT: allowHtmlTemp: infoModifiers: " + infoModifiers);
    consoleDebug("AHT: allowHtmlTemp: remoteButton: " + remoteButton);

    // Save users applications default settings
    // the await is absolutely important here!
    if ((await ahtFunctions.SaveHTMLcontentPrefs(tabId)) === false)
      return false;
    // Only go further if the previous SaveHTMLcontentPrefs function call returns true, which means
    // it actually has really saved the original prefs and isn't run into the blocked situation.

    consoleDebug("AHT: allowHtmlTemp: --------------------")
    consoleDebug("AHT: allowHtmlTemp: saved values:", ahtFunctions.savedPolicy);

    // RemoteContent popupmenu item clicked in remote content bar in a HTML message
    if (remoteButton === true) {
      consoleDebug("AHT: allowHtmlTemp: remoteButton === true");
      ahtFunctions.ShowRemote(tabId);
    }

    // We must now differ the chosen function by modifier key (ahtKeyboardEvent).

    // Addon button clicked + both CTRL and SHIFT key
    else if((infoModifiers.includes("Ctrl") || infoModifiers.includes("Command")) && infoModifiers.includes("Shift")) {
      consoleDebug("AHT: allowHtmlTemp: Addon button clicked + both CTRL and SHIFT key");
      ahtFunctions.ShowSanitizedHTML(tabId);
    }

    // Addon button clicked + only CTRL key
    else if((infoModifiers.includes("Ctrl") || infoModifiers.includes("Command")) && !(infoModifiers.includes("Shift"))) {
      consoleDebug("AHT: allowHtmlTemp: Addon button clicked + only CTRL key");
      ahtFunctions.ShowRemote(tabId);
    }

    // Addon button clicked + only SHIFT key
    else if ((infoModifiers.includes("Shift")) && !((infoModifiers.includes("Ctrl") || infoModifiers.includes("Command")))) {
      consoleDebug("AHT: allowHtmlTemp: Addon button clicked + only SHIFT key");
      ahtFunctions.ShowPlaintext(tabId);
    }

    // Addon button clicked - no key pressed
    else if (!(infoModifiers.includes("Shift") || infoModifiers.includes("Ctrl") || infoModifiers.includes("Command"))) {
      consoleDebug("AHT: allowHtmlTemp: keyboard command pressed || button clicked + no key pressed");
      consoleDebug("AHT: allowHtmlTemp: options.buttonHtmlMode = " + options.buttonHtmlMode);
      switch (options.buttonHtmlMode) {
        case "buttonMode_html":
          if (options.tempRemoteContent) {
            consoleDebug("AHT: html + tempRemoteContent");
            ahtFunctions.ShowRemote(tabId);
          } else {
            consoleDebug("AHT: html");
            ahtFunctions.ShowOriginalHTML(tabId);
          }
          break;
        case "buttonMode_sanitized":
          consoleDebug("AHT: sanitized");
          ahtFunctions.ShowSanitizedHTML(tabId);
          break;
        case "buttonMode_plaintext":
          consoleDebug("AHT: plaintext");
          ahtFunctions.ShowPlaintext(tabId);
          break;
        default:
          consoleDebug("AHT: default");
      }
    }
  },

  ShowPlaintext: async function(tabId) {
    consoleDebug("AHT: ShowPlaintext");
    try {
      let window = await messenger.windows.getCurrent();
      let updateProperties = {
        msgBodyAs: "plaintext"
      };
      await messenger.messageContentPolicy.update(window.id, updateProperties, false);
    } catch (e) {
      console.error("AHT: Plaintext error");
    }
  },

  ShowSanitizedHTML: async function(tabId) {
    consoleDebug("AHT: ShowSanitizedHTML");
    try {
      let window = await messenger.windows.getCurrent();
      let updateProperties = {
        msgBodyAs: "sanitized"
      };
      await messenger.messageContentPolicy.update(window.id, updateProperties, false);
    } catch (e) {
      console.error("AHT: ShowSanitizedHTML error");
    }
  },

  ShowOriginalHTML: async function(tabId) {
    consoleDebug("AHT: ShowOriginalHTML");
    try {
      let window = await messenger.windows.getCurrent();
      let updateProperties = {
        msgBodyAs: "original",
        // do not use false for attachmentsInline, but null to leave option unset if not tempInline
        attachmentsInline: ((options.tempInline === true) ? true : null)
      };
      await messenger.messageContentPolicy.update(window.id, updateProperties, false);
    } catch (e) {
      console.error("AHT: ShowOriginalHTML error");
    }
  },

  ShowRemote: async function(tabId) {
    consoleDebug("AHT: ShowRemote");
    try {
      let window = await messenger.windows.getCurrent();
      let updateProperties = {
        msgBodyAs: "original",
        disableRemoteContent: false,
        // do not use false for attachmentsInline, but null to leave option unset if not tempInline
        attachmentsInline: ((options.tempInline === true) ? true : null)
      };
      await messenger.messageContentPolicy.update(window.id, updateProperties, false);
    } catch (e) {
      console.error("AHT: ShowRemote error");
    }
  },

  SaveHTMLcontentPrefs: async function(tabId) {
    consoleDebug("AHT: SaveHTMLcontentPrefs");

    // We need the following block to prevent from
    // starting AHT again before the return
    // to the original settings! Otherwise we would loose
    // original settings and end up with garbled settings,
    // which would be an unwanted 'Security leak'!
    if (ahtFunctions.block === false) {
      consoleDebug("AHT: SaveHTMLcontentPrefs: ahtFunctions.block === false >>> set it to true and save the tab.id");

      ahtFunctions.block = true;
      ahtFunctions.tabId = tabId;
      ahtFunctions.registerListener();

      consoleDebug("AHT: SaveHTMLcontentPrefs: go further after ahtFunctions.registerListener()");

      ahtFunctions.savedPolicy = await messenger.messageContentPolicy.getCurrent();
      return true;
    } else {
      consoleDebug("AHT: SaveHTMLcontentPrefs: ahtFunctions.block === true >>> don't save prefs AND do not register listener");
      return false;
    }
  },

  RestoreHTMLcontentPrefs: async function() {
    consoleDebug("AHT: RestoreHTMLcontentPrefs");
    consoleDebug("AHT:", ahtFunctions.savedPolicy);

    if (ahtFunctions.block === true) {
      let window = await messenger.windows.getCurrent();
      await messenger.messageContentPolicy.update(window.id, ahtFunctions.savedPolicy, true);

      ahtFunctions.removeListener();
      ahtFunctions.tabId = 0;
      ahtFunctions.block = false;
    }
  },

}

window.addEventListener("load", function(e) {
  ahtFunctions.startup();
}, false);
