// These globals are now available from options_defaults.js
/*
var QCGlobals = {
  // border widths in unit "ex" (correspond to "thin", "medium" and "thick")
  aQC_borderwidth : [0.1667, 0.5, 0.8333],
  // border styles
  aQC_borderstyle : ["double", "solid", "dashed", "dotted"],
  // maximum quote levels
  nQC_MAX_LEVELS : 5
}
*/

var colors_fg = new Array(QCGlobals.nQC_MAX_LEVELS);
var colors_bg = new Array(QCGlobals.nQC_MAX_LEVELS);

var dm_colors_fg = new Array(QCGlobals.nQC_MAX_LEVELS);
var dm_colors_bg = new Array(QCGlobals.nQC_MAX_LEVELS);

function checkThinDouble() {
  // borderwidth "thin" and borderstyle "double" don't work together

  //  document.getElementById("graphicalquoting").checked;
  // doesn't work until diabled=true is removed
  // Default for this pref is true
  //  let graphicalquoting = document.getElementById("graphicalquoting").checked;
  let idx_borderstyle = parseInt(document.getElementById("borderStyle").value);
  let idx_borderwidth = parseInt(document.getElementById("borderWidth").value);

  var element = document.getElementById("warningThinDouble");

    //  if(graphicalquoting && idx_borderstyle==0 && idx_borderwidth==0) {
    if(idx_borderstyle==0 && idx_borderwidth==0) {
      if (element.classList.contains("hidden")) {
        element.classList.remove("hidden");
        consoleDebug("[QuoteColors] [options_ui.js] [checkThinDouble]: element.classList.remove");
      }
    } else {
      if (!element.classList.contains("hidden")) {
        element.classList.add("hidden");
        consoleDebug("[QuoteColors] [options_ui.js] [checkThinDouble]: element.classList.add");
      }
    }
//  }
}

// From top of the HTML options page to bottom to be working correctly!
function setDisabledAttribute(parentElements) {
  parentElements.forEach((parentElement) => {
    consoleDebug("[QuoteColors] [options_ui.js] [setDisabledAttribute] parentElement = " + parentElement);
  
    switch (parentElement) {
      case "enableQuoteCollapse":
        var type = "checkbox";
        var nestedElements = [
          "quoteCollapseShowFewLines",
          "quoteCollapseShowFewLinesLabelId",
          "quoteCollapseByDefault",
          "quoteCollapseByDefaultLabelId",
          "quoteCollapseOnlySubquotes",
          "quoteCollapseOnlySubquotesLabelId",
        ];
        break;
      case "quoteCollapseByDefault":
        var type = "checkbox";
        var nestedElements = [
          "quoteCollapseOnlySubquotes",
          "quoteCollapseOnlySubquotesLabelId",
        ];
        break;
      case "bordermode0":
        var type = "radio";
        var nestedElements = [
          "borderColor",
          "borderColorLabelId",
          "dm_borderColor",
          "dm_borderColorLabelId",
        ];
        break;
      case "bordermode1":
        var type = "radio";
        var nestedElements = [
          "borderColor",
          "borderColorLabelId",
          "dm_borderColor",
          "dm_borderColorLabelId",
        ];
        break;
      case "usermsgcolors":
        var type = "checkbox";
        var nestedElements = [
          "messagetextcolor",
          "dm_messagetextcolor",
          "messagetextcolorLabelId",
          "messagebgcolor",
          "dm_messagebgcolor",
          "messagebgcolorLabelId",
          "messagelinkcolor",
          "dm_messagelinkcolor",
          "messagelinkcolorLabelId",
          "messagelinkhovercolor",
          "dm_messagelinkhovercolor",
          "messagelinkhovercolorLabelId",
          "signaturecolor",
          "dm_signaturecolor",
          "signaturecolorLabelId",
          "signaturelinkcolor",
          "dm_signaturelinkcolor",
          "signaturelinkcolorLabelId",
          "enableUsermsgcolorsOnCompose",
          "enableUsermsgcolorsOnComposeLabelId",
        ];
        break;
      default:
        return;
    }

    nestedElements.forEach((element) => {
      consoleDebug("[QuoteColors] [options_ui.js] [nestedElements.forEach] element = " + element);
      if (type == "radio") {
        if ( element == "bordermode1" || "bordermode0" ) {
          if (document.querySelector('input[name=borderMode]:checked').value == 1) {
            if (document.getElementById(element).nodeName == "INPUT") {
              document.getElementById(element).removeAttribute("disabled");
            }
            else {
              document.getElementById(element).classList.remove("disabled");
            }
          } else {
            if (document.getElementById(element).nodeName == "INPUT") {
              document.getElementById(element).setAttribute("disabled", "true");
            }
            else {
              document.getElementById(element).classList.add("disabled");
            }
          }
        } 
      } else if (type == "checkbox") {
        if ((!document.getElementById(parentElement).checked) || (document.getElementById(parentElement).getAttribute("disabled"))) {
          consoleDebug("[QuoteColors] [options_ui.js] [nestedElements.forEach] disable element: " + element);
          if ((document.getElementById(element).nodeName == "INPUT") || (document.getElementById(element).nodeName == "SELECT")) {
            document.getElementById(element).setAttribute("disabled", "true");
          }
          else {
            document.getElementById(element).classList.add("disabled");
          }
        } else {
          consoleDebug("[QuoteColors] [options_ui.js] [nestedElements.forEach] enable element: " + element);
          if ((document.getElementById(element).nodeName == "INPUT") || (document.getElementById(element).nodeName == "SELECT")) {
            document.getElementById(element).removeAttribute("disabled");
          }
          else {
            document.getElementById(element).classList.remove("disabled");
          }
        }
      }
    });
  });
}

function waitAndUpdatePreview() {
  window.setTimeout(updatePreview, 200);
}

function updatePreview() {
  // update color arrays with pref values

  colors_fg[0] = document.getElementById("fg_l1").value;
  colors_bg[0] = document.getElementById("bg_l1").value;

  colors_fg[1] = document.getElementById("fg_l2").value;
  colors_bg[1] = document.getElementById("bg_l2").value;

  colors_fg[2] = document.getElementById("fg_l3").value;
  colors_bg[2] = document.getElementById("bg_l3").value;

  colors_fg[3] = document.getElementById("fg_l4").value;
  colors_bg[3] = document.getElementById("bg_l4").value;

  colors_fg[4] = document.getElementById("fg_l5").value;
  colors_bg[4] = document.getElementById("bg_l5").value;

  dm_colors_fg[0] = document.getElementById("dm_fg_l1").value;
  dm_colors_bg[0] = document.getElementById("dm_bg_l1").value;

  dm_colors_fg[1] = document.getElementById("dm_fg_l2").value;
  dm_colors_bg[1] = document.getElementById("dm_bg_l2").value;

  dm_colors_fg[2] = document.getElementById("dm_fg_l3").value;
  dm_colors_bg[2] = document.getElementById("dm_bg_l3").value;

  dm_colors_fg[3] = document.getElementById("dm_fg_l4").value;
  dm_colors_bg[3] = document.getElementById("dm_bg_l4").value;

  dm_colors_fg[4] = document.getElementById("dm_fg_l5").value;
  dm_colors_bg[4] = document.getElementById("dm_bg_l5").value;

  var colorText = document.getElementById("colorText").checked;
  var colorBackground = document.getElementById("colorBackground").checked;
  //  document.getElementById("graphicalquoting").checked;
  //  doesn't work until diabled=true is removed
  //  Default for this pref is true
  // var graphicalquoting = document.getElementById("graphicalquoting").checked;

  var borderwidth, bordercolor, dm_bordercolor, staticbordercolor, borderstyletop, borderstyleright;
  var borderstylebottom, borderstyleleft, borderstyle, collapseborders;
//  if (graphicalquoting) {
    staticbordercolor = document.querySelector('input[name=borderMode]:checked').value;
    consoleDebug("[QuoteColors] [options_ui.js] [updatePreview]: staticbordercolor: " + staticbordercolor);
    if (staticbordercolor=="1") {
      bordercolor = document.getElementById("borderColor").value;
      consoleDebug("[QuoteColors] [options_ui.js] [updatePreview]: bordercolor: " + bordercolor);
      dm_bordercolor = document.getElementById("dm_borderColor").value;
      consoleDebug("[QuoteColors] [options_ui.js] [updatePreview]: dm_bordercolor: " + dm_bordercolor);
    }

    var index_borderstyle = parseInt(document.getElementById("borderStyle").value);
    borderstyle = QCGlobals.aQC_borderstyle[index_borderstyle];
    var index_borderwidth = parseInt(document.getElementById("borderWidth").value);
    borderwidth = QCGlobals.aQC_borderwidth[index_borderwidth];

    borderstyletop = document.getElementById("borderposition_top").checked ? borderstyle : "none";
    borderstyleright = document.getElementById("borderposition_right").checked ? borderstyle : "none";
    borderstylebottom = document.getElementById("borderposition_bottom").checked ? borderstyle : "none";
    borderstyleleft = document.getElementById("borderposition_left").checked ? borderstyle : "none";

//  }
  collapseborders = document.getElementById("collapseBorders").checked;

  for (var i = 0; i < QCGlobals.nQC_MAX_LEVELS; i++) {
    var cur_elm = document.getElementById("blocklevel" + (i + 1));
    cur_elm.style.color = (colorText ? colors_fg[i] : "inherit");
    cur_elm.style.backgroundColor = (colorBackground ? colors_bg[i] : "inherit");

    var cur_qcelm = document.getElementById("qchar" + (i + 1));
    cur_qcelm.style.display = "inline";

    if (!collapseborders) cur_elm.style.padding = "1ex 2ex 1ex 2ex";
    cur_elm.style.margin = "0.5em 0em 0.5em 0em";

//    if (graphicalquoting) {
      cur_elm.style.borderColor = ((staticbordercolor=="1") ? bordercolor : colors_fg[i]);
      cur_elm.style.borderWidth = borderwidth + "ex";
      cur_elm.style.borderStyle = borderstyletop + " " + borderstyleright + " " + borderstylebottom + " " + borderstyleleft;

      cur_qcelm.style.display = "none";
      // margin-top: 0.5em to have a space under messagetext
      if (i == 0) cur_elm.style.marginTop = "0.5em";

      if (collapseborders) {
        if (i > 0) {
          // var leftmargin = (borderstyleleft == "none") ? 2.0 : 2.0 + borderwidth;
          var leftmargin = (borderstyleleft == "none") ? 1.0 : 1.0;
          // var rightmargin = (borderstyleright == "none") ? 2.0 : 2.0 + borderwidth;
          var rightmargin = (borderstyleright == "none") ? 1.0 : 1.0;
          cur_elm.style.marginLeft = "-" + leftmargin + "ex";
          cur_elm.style.marginRight = "-" + rightmargin + "ex";
        }
        cur_elm.style.padding = "0ex 2ex 0ex 2ex";
      }
//    } else {
//      cur_elm.style.borderStyle = "none";
//      cur_elm.style.padding = "0.5em 0em 0em 0em";
//      if (i == 0) cur_elm.style.marginTop = "1.5em";
//    }
  }
  // if (!graphicalquoting || collapseborders)
  if (collapseborders)
    document.getElementById("blocklevel5").style.paddingBottom = "0.5em";

  //********** Generate Preview Style for Darkmode ******************/
  //
  for (var i = 0; i < QCGlobals.nQC_MAX_LEVELS; i++) {
    var cur_elm = document.getElementById("dm_blocklevel" + (i + 1));
    cur_elm.style.color = (colorText ? dm_colors_fg[i] : "inherit");
    cur_elm.style.backgroundColor = (colorBackground ? dm_colors_bg[i] : "inherit");

    var cur_qcelm = document.getElementById("dm_qchar" + (i + 1));
    cur_qcelm.style.display = "inline";

    if (!collapseborders) cur_elm.style.padding = "1ex 2ex 1ex 2ex";
    cur_elm.style.margin = "0.5em 0em 0.5em 0em";

//    if (graphicalquoting) {
      cur_elm.style.borderColor = ((staticbordercolor=="1") ? dm_bordercolor : dm_colors_fg[i]);
      cur_elm.style.borderWidth = borderwidth + "ex";
      cur_elm.style.borderStyle = borderstyletop + " " + borderstyleright + " " + borderstylebottom + " " + borderstyleleft;

      cur_qcelm.style.display = "none";
      // margin-top: 0.5em to have a space under messagetext
      if (i == 0) cur_elm.style.marginTop = "0.5em";

      if (collapseborders) {
        if (i > 0) {
          // var leftmargin = (borderstyleleft == "none") ? 2.0 : 2.0 + borderwidth;
          var leftmargin = (borderstyleleft == "none") ? 1.0 : 1.0;
          // var rightmargin = (borderstyleright == "none") ? 2.0 : 2.0 + borderwidth;
          var rightmargin = (borderstyleright == "none") ? 1.0 : 1.0;
          cur_elm.style.marginLeft = "-" + leftmargin + "ex";
          cur_elm.style.marginRight = "-" + rightmargin + "ex";
        }
        cur_elm.style.padding = "0ex 2ex 0ex 2ex";
      }
//    } else {
//      cur_elm.style.borderStyle = "none";
//      cur_elm.style.padding = "0.5em 0em 0em 0em";
//      if (i == 0) cur_elm.style.marginTop = "1.5em";
//    }
  }
  // if (!graphicalquoting || collapseborders)
  if (collapseborders)
    document.getElementById("dm_blocklevel5").style.paddingBottom = "0.5em";
  //
  // *********** End Generate Preview Style for Darkmode **************/
  
  updatePreviewTextAndBg();
}

function updatePreviewTextAndBg() {
  if (document.getElementById("usermsgcolors").checked) {
    var msgtextcolor = document.getElementById("messagetextcolor").value;
    var msgbgcolor = document.getElementById("messagebgcolor").value;
    var dm_msgtextcolor = document.getElementById("dm_messagetextcolor").value;
    var dm_msgbgcolor = document.getElementById("dm_messagebgcolor").value;
  } else {
    var msgtextcolor = "#000000";
    var msgbgcolor = "#FFFFFF";
    var dm_msgtextcolor = "#F9F9FA";
    var dm_msgbgcolor = "#202023";
  }
  document.getElementById("previewboxcontent").style.color = msgtextcolor;
  document.getElementById("previewboxcontent").style.backgroundColor = msgbgcolor;
  document.getElementById("dm_previewboxcontent").style.color = dm_msgtextcolor;
  document.getElementById("dm_previewboxcontent").style.backgroundColor = dm_msgbgcolor;
}

async function testCommandKey(optionKey, defaultValue, testName, testValue) {
  consoleDebug("[QuoteColors] [options_ui_listeners.js] testCommandKey: " + testName + " = " + testValue);

  let detail = {};
  detail.name = testName;
  detail.shortcut = testValue;

  if(detail.shortcut === "") {
    consoleDebug("[QuoteColors]: testCommandKey: Your chosen command key is empty. Therefore the default \"" + defaultValue + "\" will be used.");
    detail.shortcut = defaultValue;
    await browser.commands.update(detail);
    await messenger.storage.local.remove(optionKey);
    return false;
  }

  try {
    await browser.commands.update(detail);
    return true;
  } catch (e) {
    consoleDebug("[QuoteColors]: testCommandKey: Your chosen command key isn't valid. Therefore the default \"" + defaultValue + "\" will be used.");
    detail.shortcut = defaultValue;
    await browser.commands.update(detail);
    await messenger.storage.local.remove(optionKey);
    return false;
  }
}

function showCommandKeyWarning(warningId, doWarn) {
  if(doWarn) {
    let element = document.getElementById(warningId);
    if (element.classList.contains("hidden")) {
      element.classList.remove("hidden");
      consoleDebug("[QuoteColors] [options_ui_listeners.js] " + warningId + ": element.classList.remove");
    }
  } else {
    let element = document.getElementById(warningId);
    if (!element.classList.contains("hidden")) {
      element.classList.add("hidden");
      consoleDebug("[QuoteColors] [options_ui_listeners.js] " + warningId + ": element.classList.add");
    }
  }
}
