/*jslint         browser : true, continue : true,
  devel  : true, indent  : 2,    maxerr   : 50,
  newcap : true, nomen   : true, plusplus : true,
  regexp : true, sloppy  : true, vars     : false,
  white  : true
*/

/*global $, app */

app.inbox = (function() {
  "use strict";
  //---------------- BEGIN MODULE SCOPE VARIABLES --------------
  var stateMap = {},
    configModule,
    initModule,
    terminateModule,
    getMessages, 
    timerVar=null;
  //----------------- END MODULE SCOPE VARIABLES ---------------

  //------------------- BEGIN UTILITY METHODS ------------------
  getMessages = function() {
    stateMap.$appList.html("<h4>Checking...</h4>");

    app.api.get("mail/salesandsupportsummaries", function(res) {
      if (res.error) {
        $.gevent.publish("app-show-error", res.msg);
      } else {
        stateMap.$appList.empty();
        var newMessageCount = 0;
        var lastAccount = "";
        //The list
        var displayedItems = 0;
        var generatedHtml = '<ul class="list-group">';

        //Iterate the results
        for (var y = 0; y < res.length; y++) {
          var obj = res[y];
          if (!obj.flags.includes("deleted")) {
            if (!obj.flags.includes("seen")) {
              newMessageCount++;
            }
            var displayClass = obj.flags.includes("seen")
              ? "border-secondary text-secondary"
              : "border-primary text-primary";
            var answeredIconClass = obj.flags.includes("answered")
              ? " mdi mdi-reply"
              : "";

            //Make a group on change of account
            if (lastAccount !== obj.account) {
              lastAccount = obj.account;
              //Insert as 'header' in list
              generatedHtml +=
                '<li class="list-group-item active">' + lastAccount + "</li>";
            }

            //LIST ITEM
            generatedHtml +=
              '<li class="list-group-item" ><a href="#!/mailEdit/' +
              obj.account +
              "/Inbox/" +
              obj.id +
              "\"><span class='" +
              displayClass +
              answeredIconClass +
              "'>" +
              obj.subject +
              "&nbsp;-&nbsp;" +
              obj.from +
              "</span></a></li>";
            displayedItems++;
          } //if not deleted
        } //loop

        //Nothing to display?
        if (!displayedItems) {
          generatedHtml +=
            '<li class="list-group-item">NO MESSAGES - ' +
            moment().format("YYYY-MM-DD LT") +
            "</li>";
        }

        //close list group
        generatedHtml += "</ul>";

        generatedHtml +=
          '<div class="mt-5"><h6><small class="text-muted">Last check: ' +
          moment().format("YYYY-MM-DD LT") +
          "</small><h6></div>";
        //SET IT
        stateMap.$appList.append(generatedHtml);

        //case 3516
        if (newMessageCount > 0) {
          document.title =
            newMessageCount +
            " NEW message" +
            (newMessageCount == 1 ? "" : "s");
        } else {
          document.title = "No new messages";
        }
      }
      //do it every 5 minutes
      timerVar=setTimeout(getMessages,5*60*1000);
      //timerVar=setTimeout(getMessages,5000);
      console.log("INBOX.GETMESSAGES - started timer " + timerVar);
    });
  };
  //-------------------- END UTILITY METHODS -------------------

  //------------------- BEGIN EVENT HANDLERS -------------------
  //-------------------- END EVENT HANDLERS --------------------

  //------------------- BEGIN PUBLIC METHODS -------------------
  //CONFIGMODULE
  //
  configModule = function(context) {
    stateMap.context = context.context;
    if (stateMap.context.params.id) {
      stateMap.id = stateMap.context.params.id;
    }
  };

  //INITMODULE
  //
  initModule = function($container) {
    if (typeof $container === "undefined") {
      $container = $("#app-shell-main-content");
    }
    $container.html(Handlebars.templates["app.inbox"]({}));
    stateMap.$appList = $("#rf-list-div");

    getMessages();

    //auto refresh every 10 minutes
    
    // intervalRef = setInterval(function() {
    //   getMessages();
    // }, 10 * 60 * 1000);

    app.nav.contextClear();
    ////app.nav.setContextTitle("inbox");
  };

  // TERMINATE MODULE
  //
  terminateModule = function() {
    
    if(timerVar!=null){
      clearTimeout(timerVar);
      console.log("INBOX.TERMINATEMODULE - cleared timer" + timerVar);
    }
    //clear up event handler
    // clearInterval(intervalRef);
    // intervalRef=null;
    //console.log("INBOX.TERMINATEMODULE");
  };

  //PUBLIC METHODS
  //
  return {
    configModule: configModule,
    initModule: initModule,
    terminateModule: terminateModule
  };
  //------------------- END PUBLIC METHODS ---------------------
})();
