// encoding='UTF-8'

/*
  # File : xnote-window.xul
  # Authors : Hugo Smadja, Lorenz Froihofer, Klaus Buecher
  # Description : Functions associated with the XNote window (xnote-window.xul).
*/
var { XPCOMUtils } = ChromeUtils.import ?  ChromeUtils.import('resource://gre/modules/XPCOMUtils.jsm')
  :  ChromeUtils.importESModule("resource://gre/modules/XPCOMUtils.sys.mjs");
//var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
//var Services = globalThis.Services || ChromeUtils.import("resource://gre/modules/Services.jsm").Services;


XPCOMUtils.defineLazyScriptGetter(
  this,
  "PrintUtils",
  "chrome://messenger/content/printUtils.js"
);

var { xnote } = ChromeUtils.import ?  ChromeUtils.import("resource://xnote/modules/xnote.jsm")
  :  ChromeUtils.importESModule("resource://xnote/modules/xnote.sys.mjs");

// This object lives inside the xnote window. This is the old 
// xnote.ns.Window object, which was falsly placed in the global xnode module.
window.xnoteWindowObj = function () {
  // Variables for window movement
  var xBeforeMove, yBeforeMove;
  // Variables for window resizing.
  var widthBeforeMove, heightBeforeMove;

  var oldOpenerX, oldOpenerY;

  /** Displayed note. */
  var note;

  // result
  var pub = {};

  /**
   * APPELANT
   * type	: évènement load de l'élément XUL <window>
   * id	: xnote-window
   * FONCTION
   * Exécutée au chargement du post-it avant qu'elle ne soit affichée à l'écran.
   * C'est ici, que l'on peut modifier le style de la fenêtre dynamiquement
   */


  pub.keys = [],
  pub.timeout = false, // holder for timeout id
  pub.delay = 250, // delay after resize event is "complete" to run callback
  pub.calls = 0;

    pub.onBlur = function () {
      pub.saveNote();
      //  window.xnoteWindowObj.updateTag
      let texte = self.document.getElementById('xnote-texte');
      pub.updateTag(texte.value);
    },
    pub.onLoad = async function (e) {
      //~ dump('\n->onLoad');
      // premet l'accès au préférences
      /*try
      {
        self.document.getElementById('xnote-note').style.setProperty('-moz-opacity', pref.getIntPref('xnote.transparence')/10, '');
      }
      catch(e) {}*/

      Services.scriptloader.loadSubScript("chrome://xnote/content/scripts/notifyTools.js", pub, "UTF-8");

      let closeKey = await pub.notifyTools.notifyBackground({ command: "getCommandKey" });

      //console.log("wind", window, window.opener, opener, typeof(window.addEventListener), opener === window.opener,addEventListener===window.addEventListener , typeof(addEventlistener));

      pub.keys["Alt"] = false;
      pub.keys["Shift"] = false;
      pub.keys["Ctrl"] = false;
      pub.keys["key"] = "";


      let comm = await closeKey.shortcut.split("+");
      pub.keys["key"] = comm[comm.length - 1].toLowerCase();
      for (let i = comm.length - 2; i > -1; i--) {
        pub.keys[comm[i]] = true;
      };
      //   console.log("leg", closeKey, pub.keys, comm);



      // Capture the Window focus lost event to update the XNote tag.
      addEventListener('blur', window.xnoteWindowObj.onBlur, true);
      addEventListener('unload', window.xnoteWindowObj.onUnload, false);
      //window.addEventListener("resize", window.xnoteWindowObj.resize, false);


      //or use onbeforeunload
       window.addEventListener('resize', function() {
        // clear the timeout
        clearTimeout(window.xnoteWindowObj.timeout);
        // start timing for event "completion"
        timeout = setTimeout(window.xnoteWindowObj.resizeEvent, window.xnoteWindowObj.delay);
      });     //Necessary for correct shutdown as we are otherwise unable to correctly
      //save a modified note
      opener.addEventListener("unload", window.xnoteWindowObj.onOpenerUnload, false);
      //Unfortunately, there seems to be no better way to react on window
      //movement.
      setInterval(window.xnoteWindowObj.checkOpenerMoved, 500);

      note = self.arguments[0];

      let texte = self.document.getElementById('xnote-texte');
      texte.value = note.text;
      texte.textContent = note.text;
      autosize(texte);

      //if the same key opens and closes, we need this, otherwise the window closes immediately
      setTimeout(() => { texte.addEventListener("keyup", window.xnoteWindowObj.onInput, false); }, 300);
   //   let fwd = self.document.getElementById('xnote-button-forward');
   //??   fwd.href = "mailto:?body=" + encodeURI(note.text);

      //PrintUtils.showPageSetup();
      //self.print();


      //set date in the titlebar
      // let modificationdate = self.document.getElementById("xnote-mdate");
      // modificationdate.value = note.modificationDate;

      document.title = "XNote  " + note.modificationDate;



      self.setTimeout(window.xnoteWindowObj.resizeWindow, 0);

      if (window.arguments[1]) {
        texte.focus();
        //        console.log("wnd has arg 1");
      }
      else {
        self.setTimeout(window.opener.focus, 0);
        //~ dump('\n<-onLoad');
        //      console.log("wnd has no arg 1");
      }
    }

  function resizeWindow(width, height) {
    width = width < 58 ? 58 : width;
    //Consider background image for height because of textarea.
    height = height < 130 ? 130 : height;
    //~ dump('\nwidth='+width+', height='+height);
    window.resizeTo(width, height);
    document.getElementById("xnote-texte").style.height = (height - 40) + "px";
  }

  pub.resizeWindow = function () {
    resizeWindow(note.width, note.height);
  }

  pub.onInput = function (ev) {
    // console.log("ev", ev);
    if ((ev.key == pub.keys["key"]) && (ev.altKey == pub.keys["Alt"]) && (ev.shiftKey == pub.keys["Shift"]) && (ev.ctrlKey == pub.keys["Ctrl"])) {
      //  console.log("got it");
      //  pub.saveNote();  done in onUnload
      window.close();
    };
  }

  /**
   * CALLING XUL
   * Type: blur event of the XUL element <window>
   * Id: XNote-window
   * FUNCTION
   * Function called when the window loses focus. It assigns a
   * tag to the selected mail if the note contains text.
   */
  pub.updateTag = function () {
    //~ dump('\n->updateTag');
    //  opener.gTabmail.currentAbout3Pane.xnoteOverlayObj.updateTag(document.getElementById('xnote-texte').value);
    //102
    let texte = self.document.getElementById('xnote-texte');

    opener.xnoteOverlayObj.updateTag(texte.value);
    //~ dump('\n<-updateTag');
  }

  /**
   * CALLER XUL
   * Type: unload event in XUL element <window>
   * Id: XNote-window
   * FUNCTION
   * Saves the note: location, size and content of the note,
   * A blank note will be deleted.
   */
  pub.saveNote = function () {
    let dateformat = xnote.ns.Commons.xnotePrefs.dateformat;
    let date = xnote.ns.DateFormat;
    let dateStr = date.format(dateformat);
    //~ dump('\n->saveNote');
    if (note.modified) {
      let oldText = note.text;
      note.text = document.getElementById('xnote-texte').value;
      if (note.text != '') {
        note.x = window.screenX - opener.screenX;
        note.y = window.screenY - opener.screenY;
        note.width = window.innerWidth;
        note.height = window.innerHeight;
        if (oldText != note.text) {
          note.modificationDate = dateStr;
        }
        note.saveNote();
      }
      else {
        note.deleteNote();
      }
    }
    //  ~ dump('\n<-saveNote');
  }


  /**
   * CALLER XUL
   * Type: event input from XUL element <html:input>
   * Id: text
   * FUNCTION
   * Notification that the note was modified (edited, moved, ...).
   */
  pub.noteModified = function () {
    //~ dump('\n->modifierNote');
    note.modified = true;
    //~ dump('\n<-modifierNote');
  }

  pub.bookmarkNote = function () {
    pub.notifyTools.notifyBackground({ command: "setBookmark" });
  }

  pub.printNote = function () {
    //window.document.documentElement.textContent= note.text;
//       console.log("printwindow", window.document, "docEl", window.document.documentElement , "text", window.document.documentElement.textContent, window);

    //  console.log("note", xnote.text);
  //  window.print();
  //  self.print();
    // window.document.print();
    //window.top = window;
    //window.currentWindowGlobal = window;
    //PrintUtils.printWindow(window, {});
//debugger;
    let mainWindow = Services.wm.getMostRecentWindow("mail:3pane");
    /* */
    let messageBrowser = mainWindow.document.getElementById("messagepane");//messagepane
//    console.log("op", window.opener, opener);

 //   let a3p =  mainWindow.gTabmail.currentTabInfo.chromeBrowser.contentWindow;
    let a3p =  mainWindow.gTabmail.currentAbout3Pane;//.gTabmail.currentTabInfo.chromeBrowser.contentWindow;
    messageBrowser = a3p.document.getElementById("messageBrowser");//messagepane
    let messagePaneBrowser = a3p.document.getElementById("xnote-print");
//    console.log("befbody",  messageBrowser, messagePaneBrowser);

    let msgBody = messageBrowser.contentDocument.getElementsByTagName("body"); //documentElement.
//     console.log("body", msgBody, messageBrowser.contentWindow, messageBrowser.contentWindow.document, messageBrowser.contentDocument.children[0].children[2],
//      messageBrowser.contentWindow.document.body,messageBrowser.contentWindow.document.body.children
//     );
 //    messagePaneBrowser = a3p.document.getElementById("xnote-print");
    messagePaneBrowser.setAttribute('style', 'white-space: pre-line;');
    let modificationdate = self.document.getElementById("xnote-mdate");
    let docEl = messagePaneBrowser.contentDocument.documentElement;
    let doc = messagePaneBrowser.contentDocument;
    var p = doc.createElement("p");
    p.appendChild(doc.createTextNode(document.title));//modificationdate.value));
    docEl.appendChild(p);
    docEl.appendChild(doc.createElement("br"));
    p = doc.createElement("p");
    p.appendChild(doc.createTextNode(note.text));
    docEl.appendChild(p);

    docEl.appendChild(doc.createElement("br"));
    let hr = doc.createElement("br");

    docEl.appendChild(hr);

    /* 
    NodeList.prototype.forEach = Array.prototype.forEach;
    var children = messageBrowser.contentWindow.document.body.childNodes;//msgBody.childNodes;
    children.forEach(function (item) {
//      var cln = item.cloneNode(true);
 //     docEl.appendChild(cln);
      let cln = doc.importNode(item, true);
    });
   */
    //messagePaneBrowser.contentDocument.documentElement.textContent =
    //"XNote " +modificationdate.value +"\r\n" + note.text;//"eee";
    mainWindow.PrintUtils.startPrintWindow(messagePaneBrowser.browsingContext, {});


    // messagePaneBrowser.contentDocument.documentElement.textContent = "";
    /*debugger;
    let messagePaneBrowser =document.getElementById("bb");  
   // messagePaneBrowser.top = window;
    //messagePaneBrowser.currentWindowGlobal = window;
    //messagePaneBrowser.top = window;
    //messagePaneBrowser.currentWindowGlobal = window;
  //  console.log("msbro", messagePaneBrowser);
    messagePaneBrowser.contentDocument.documentElement.textContent = "eee";
    //messagePaneBrowser.contentDocument.textContent = "jjj";
  //  console.log("brodoc", messagePaneBrowser.contentDocument);
    mainWindow.PrintUtils.startPrintWindow(messagePaneBrowser.browsingContext, {});
   
    var printContents = document.getElementById("xnote-texte").cloneNode(true);
   
    w = window.open();
    w.document.body.appendChild(printContents);
    w.print();
    w.close();
    
    let childWindow =window.open('', '', 'height=600,width=800');;// window.open('','childWindow','location=yes, menubar=yes, toolbar=yes');
    childWindow.document.open();
    childWindow.document.write('<html><head></head><body>');
    childWindow.document.write(xnote.text);
    //childWindow.document.write(document.getElementById('targetTextArea').value.replace(/\n/gi,'<br>'));
    childWindow.document.write('</body></html>');
    childWindow.print();
    childWindow.document.close();
    childWindow.close();
   /*
   
    <browser id="messagepane"
                    context="mailContext"
                    tooltip="aHTMLTooltip"
                    style="height: 0px; min-height: 1px"
                    flex="1"
                    name="messagepane"
                    disablesecurity="true"
                    disablehistory="true"
                    type="content"
                    primary="true"
                    autofind="false"
                    src="about:blank"
                    messagemanagergroup="single-page"
                    onclick="return contentAreaClick(event);"
                    onresize="return messagePaneOnResize(event);"/> */
  }

  pub.forwardNote = function () {

    self.print();
  }


  pub.searchXNotes = function () {
    // console.log("xnote search clicked");
    //  window.close();
    pub.notifyTools.notifyBackground({ command: "searchXNotes" });

  }


  pub.copyNoteToClipboard = function () {
    let clipboard = Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper);
    clipboard.copyString(note.text);
    /*
  //  console.log("wnd", window, "doc", window.document);
     var res;
     window.document.designMode = "on";
    // let docb = window.document.getElementById("body");
    // console.log("body", docb);
     res = window.document.execCommand("selectAll");
   //  console.log("selectAll", res);
  
     res = window.document.execCommand("copy");
  //   console.log("copy", res);
   */
  }


  /**
   * CALLER XUL
   * Type: event input from XUL element <html:input>
   * Id: text
   * FUNCTION
   * Change the set the note to be modified the note to be deleted when
   * the save method is called.
   */
  pub.deleteNote = function () {
    //~ dump('\n->supprimerNote');
    document.getElementById('xnote-texte').value = '';
    pub.noteModified();
    //to correctly set tag
    note.text = "";
    note.saveNote();
    opener.xnoteOverlayObj.updateTag("");
    //~ dump('\n<-supprimerNote');
  }

  /**
   * APPELANT XUL
   * type	: évènement mousedown de l'élément XUL <html:input>
   * id	: redim
   * FONCTION
   * Quand le bouton de la souris est enfoncé, sauve la taille et
   * lance la capture des évènements de déplacement et de relâchement
   */
  pub.startRedimensionnement = function (e) {
    if (e.button == 0) {
      xBeforeMove = e.screenX;
      widthBeforeMove = window.innerWidth;
      yBeforeMove = e.screenY;
      heightBeforeMove = window.innerHeight;
      //~ dump('\n xBeforeMove='+xBeforeMove+' ; yBeforeMove='+yBeforeMove);
      //~ dump('\n heightBeforeMove='+heightBeforeMove+' ; heightBeforeMove='+heightBeforeMove);
      document.addEventListener('mousemove', window.xnoteWindowObj.redimenssionnement, true);
      document.addEventListener('mouseup', window.xnoteWindowObj.stopRedimenssionnement, true);
    }
  }

  /**
   * lors du déplacement de la souris, redimensionne la fenêtre grâce à la taille
   * enregistrée lors du clic.
   */
  pub.redimenssionnement = function (e) {
    //~ dump('\n w.document.width='+window.document.width+' ; w.document.height='+window.document.height);
    //console.log("redimenssionnement");
    //~ dump('\nlargeur='+document.getElementById('xnote-texte').style.width);
    let newWidth = widthBeforeMove + e.screenX - xBeforeMove;
    let newHeight = heightBeforeMove + e.screenY - yBeforeMove;
    //~ dump('\nxAvantDeplacement='+xBeforeMove+', yAvantDeplacement='+yBeforeMove);
    //~ dump('\ne.screenX='+e.screenX+', e.screenY='+e.screenY);
    resizeWindow(newWidth, newHeight);
    pub.noteModified();
  }

  pub.resizeEvent = function (ev) { //not working
    // console.log("resize");
    //window.resizeTo(width, height);
 //   document.getElementById("xnote-texte").style.height = (window.innerHeight - 40) + "px";
    pub.noteModified();
    //redraw textarea
//    const t = window.document.createElement('span');
    let st = window.document.getElementById('xnote-note');
//    st.appendChild(t);
//    setTimeout(() => { st.removeChild(t) }, 0);
let ht = st.style.height;
//console.log("ht", ht);
  
    var element = document.getElementById('xnote-texte');
    element.style.height = "100%";//"calc(100% - 10px)";
    var n = document.createTextNode(' ');
    var disp = element.style.display;  // don't worry about previous display style
    
//    element.appendChild(n);
 //   element.style.display = 'none';
    
//    setTimeout(function(){
//        element.style.display = disp;
//        n.parentNode.removeChild(n);
 //   },20); // you can play with this timeout to make it as short as possible
    //resizeWindow(window.innerWidth, window.innerHeight);
    autosize(element);

  },

  pub.resize = function () { //not working
    // console.log("resize");
    //window.resizeTo(width, height);
    document.getElementById("xnote-texte").style.height = (window.innerHeight - 40) + "px";

    //resizeWindow(window.innerWidth, window.innerHeight);


  },
    /**
     * quand le bouton de la souris est relaché, on supprime la capture
     * du déplacement de la souris.
     */
    pub.stopRedimenssionnement = function (e) {
      document.removeEventListener('mousemove', window.xnoteWindowObj.redimenssionnement, true);
      document.removeEventListener('mouseup', window.xnoteWindowObj.stopRedimenssionnement, true);
      let texte = document.getElementById('xnote-texte');
      texte.focus();
    }

  pub.checkOpenerMoved = function () {
    if (oldOpenerX != opener.screenX || oldOpenerY != opener.screenY) {
      window.moveTo(opener.screenX + note.x, opener.screenY + note.y)
      oldOpenerX = opener.screenX;
      oldOpenerY = opener.screenY;
    }
  }

  pub.onUnload = function (e) {
    //  console.log("unload XNote wnd");
    //    ~dump("\n->onUnload");
    //console.log("note unLoad");
    pub.saveNote();
    let texte = self.document.getElementById('xnote-texte');
    pub.updateTag(texte.value);
    removeEventListener('blur', window.xnoteWindowObj.onBlur);
    removeEventListener('load', window.xnoteWindowObj.onLoad);
    removeEventListener('unload', window.xnoteWindowObj.onUnload);
    opener.removeEventListener("unload", window.xnoteWindowObj.onOpenerUnload);
    texte.removeEventListener("keyup", window.xnoteWindowObj.onInput);
    //  window.removeEventListener("resize", window.xnoteWindowObj.redimenssionnement);
  }

  pub.onOpenerUnload = function (e) {
    pub.saveNote();
  }

  return pub;
}();

addEventListener('load', window.xnoteWindowObj.onLoad, false);
