// Set enabled/disabled status for toolbar / message header button in multiple steps
// Step 1.1: disable if message selection changes (to catch one versus multiple)

async function registerListeners() {
  messenger.mailTabs.onSelectedMessagesChanged.addListener(async (tab, selectedMessages) => {
    consoleDebug("AHT: mailTabs.onSelectedMessagesChanged: disable toolbar button if selected messages != 1");
    consoleDebug("AHT: Object.keys(selectedMessages.messages).length = " + Object.keys(selectedMessages.messages).length);

    // Allways disable the button, and decide in the other (following) listeners to re-enable the button.
    // Contra: This leads to a short button "blinking" (off-on).
    // Pro:    In Offline Mode the button is disabled (as intended), if the message body is not available and no message is displayed
    disableButtons(tab.id);

    // This would be the alternative to allways disabling the button, but the button will then not be disabled in the following 
    // listeners below, when no message body is available in Offline Mode.
    /*
    if(Object.keys(selectedMessages.messages).length != 1) {
      disableButtons(tab.id);
    }
    */
  });
  
  // Step 1.2: disable if folder is changed
  messenger.mailTabs.onDisplayedFolderChanged.addListener(async (tab, displayedFolder) => {
    consoleDebug("AHT: mailTabs.onDisplayedFolderChanged: disable toolbar button");
  
    disableButtons(tab.id);
  });
  
  // Step 1.3: disable if tab is changed
  messenger.tabs.onActivated.addListener(async (activeInfo) => {
    consoleDebug("AHT: tabs.onActivated: disable toolbar button");
  
    disableButtons(activeInfo.tabId);
  });
  
  // Step 3: enable / disable if junk status changes
  //
  // Commented out since the junk status change will now (Thunderbird 101+) fire onMessageDisplayed again for 
  // all opened instances of a message. So it isn't necessary to listen for the onUpdated event, which would 
  // be more complicated, and the code below was not yet complete and not really working.
  //
  /**********************************************************************************************************
  messenger.messages.onUpdated.addListener(async (message, changedProperties) => {
    consoleDebug("AHT: messages.onUpdated: changedProperties.junk: " + changedProperties.junk);
    consoleDebug("AHT: messages.onUpdated: changedProperties message.id: " + message.id);

    ////////////////// The following code in this listener has be reworked. /////////////////////////////
    // The goal is to catch all tabs and windows in which the relevant message is shown, 
    // to dis- or enable the Button according to the junk status, 
    // which has changed after the inital display of the message.
    let MessageHeaderUpdated = message;
    let MailTab = await messenger.mailTabs.getCurrent();
    // MailTab sometimes is undefined, so so use if(MailTab) to prevent errors in console
    if (MailTab) {
      consoleDebug("AHT: messages.onUpdated: changedProperties: displayed MailTab.id = " + MailTab.id);
      let MessageHeaderDisplayed = await messenger.messageDisplay.getDisplayedMessage(MailTab.id);
      if (MessageHeaderUpdated.headerMessageId == MessageHeaderDisplayed.headerMessageId) {
        consoleDebug("AHT: messages.onUpdated: changedProperties headerMessageId == messages displayed headerMessageId");
      }
    }
    // disableButtons(activeInfo.tabId);
  });
  **********************************************************************************************************/

  // Step 2: re-enable if really a (one) message is displayed
  //         - and it is not Junk
  //         - and it is not News
  //         - and it has a HTML MIME part
  messenger.messageDisplay.onMessageDisplayed.addListener(async (tab, message) => {
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: tab.id = " + tab.id + " message.id = " + message.id);
  
    // disableButtons(tab.id);
  
    // check for folder type and don't enable UI for junk folders
    let MessageHeader = await messenger.messages.get(message.id)
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: folder type = " + MessageHeader.folder.type);
    if (MessageHeader.folder.type == "junk") {
      disableButtons(tab.id);
      return;
    }
    // check for junk status and don't enable UI for junk messages
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: junk status = " + MessageHeader.junk);
    if (MessageHeader.junk) {
      disableButtons(tab.id);
      return;
    }

    // check for account type:
    // don't enable UI for News accounts,
    // but enable UI for RSS accounts
    let account = await messenger.accounts.get(message.folder.accountId);
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: account type = " + account.type);
    if (account.type == "news") {
      disableButtons(tab.id);
      return;
    }
    if (account.type == "rss") {
      consoleDebug("AHT: messageDisplay.onMessageDisplayed: enable toolbar button");
      enableButtons(tab.id);
      return;
    }
  
    // for all other messages check, if they have a HTML MIME part
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: checkMailForHtmlpart");
  
    let hasHtmlMimePart = await messenger.allowHtmlTemp.checkMailForHtmlpart(message.id, options.debug);
  
    consoleDebug("AHT: messageDisplay.onMessageDisplayed: checkMailForHtmlpart returns: " + hasHtmlMimePart);
  
    if(hasHtmlMimePart) {
      enableButtons(tab.id);
    } else {
      disableButtons(tab.id);
    }
  });

  // Listen for option changes to set the button icon and label
  await messenger.storage.onChanged.addListener(setButtonIconAndLabel);
  // Listen for option changes to set the command key
  await messenger.storage.onChanged.addListener(setCommandKey);

  // Listen for prefs changes using the messageContentPolicy API
  await messenger.messageContentPolicy.onChanged.addListener(async (newValue) => {
    consoleDebug("AHT: messageContentPolicy newValue:", newValue);
    await setButtonIconAndLabel();
  });

  consoleDebug("AHT: registered initial listeners for update_ui.js: ");
}

async function setButtonIconAndLabel() {
  buttonIcon = {};
  buttonLabel = {};

  await reloadOption("buttonHtmlMode");
  let appRemoteContent = !(await messenger.messageContentPolicy.getCurrent()).disableRemoteContent;
  await reloadOption("tempRemoteContent");
  consoleDebug("AHT: setButtonIcon: options.buttonHtmlMode: " + options.buttonHtmlMode);
  consoleDebug("AHT: setButtonIcon: pref appRemoteContent: " + appRemoteContent);
  consoleDebug("AHT: setButtonIcon: options.tempRemoteContent: " + options.tempRemoteContent);

  switch (options.buttonHtmlMode) {
    case "buttonMode_html":
      if((appRemoteContent == true) || (options.tempRemoteContent == true)) {
        consoleDebug("AHT: setButtonIcon: html+");
        buttonIcon.path = "../icons/aht_button_supernova_color_plus.svg";
        buttonLabel.label = messenger.i18n.getMessage("button_label_html");
        break;
      } else {
        consoleDebug("AHT: setButtonIcon: html");
        buttonIcon.path = "../icons/aht_button_supernova_color.svg";
        buttonLabel.label = messenger.i18n.getMessage("button_label_html");
        break;
      }
    case "buttonMode_sanitized":
      consoleDebug("AHT: setButtonIcon: sanitized");
      buttonIcon.path = "../icons/aht_button_supernova_sanitized.svg";
      buttonLabel.label = messenger.i18n.getMessage("button_label_sanitized");
      break;
    case "buttonMode_plaintext":
      consoleDebug("AHT: setButtonIcon: plaintext");
      buttonIcon.path = "../icons/aht_button_supernova_plaintext.svg";
      buttonLabel.label = messenger.i18n.getMessage("button_label_plaintext");
      break;
    default:
      consoleDebug("AHT: setButtonIcon: default");
      buttonIcon.path = "../icons/aht_button_supernova_color.svg";
      buttonLabel.label = messenger.i18n.getMessage("button_label_html");
      break;
    }

  messenger.browserAction.setIcon(buttonIcon);
  messenger.browserAction.setLabel(buttonLabel);
  messenger.messageDisplayAction.setIcon(buttonIcon);
  messenger.messageDisplayAction.setLabel(buttonLabel);
}

function enableButtons(tabId) {
  messenger.messageDisplayAction.enable(tabId);
  messenger.browserAction.enable(tabId);
}

function disableButtons(tabId) {
  messenger.messageDisplayAction.disable(tabId);
  messenger.browserAction.disable(tabId);
}

async function setCommandKey() {
  await reloadOption("commandKey");
  consoleDebug("AHT: setCommandKey: options.commandKey: " + options.commandKey);

  let detail = {};
  detail.name = "_execute_message_display_action";
  detail.shortcut = options.commandKey;
  if(detail.shortcut === "") {
    consoleDebug("AHT: setCommandKey: Your chosen commandkey is empty. Therefore the default \"" + DefaultOptions.commandKey + "\" will be used.");
    detail.shortcut = DefaultOptions.commandKey;
  }
  try {
    await messenger.commands.update(detail);
  } catch (e) {
    consoleDebug("AHT: setCommandKey: Your chosen commandkey isn't valid. Therefore the default \"" + DefaultOptions.commandKey + "\" will be used.");
    detail.shortcut = DefaultOptions.commandKey;
    await messenger.commands.update(detail);
    // Reset option to default
    return messenger.storage.local.remove("commandKey").then(() => {
    });
  }
}

registerListeners();
setButtonIconAndLabel();
setCommandKey();