/*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.customers = (function() {
  "use strict";
  //---------------- BEGIN MODULE SCOPE VARIABLES --------------
  var stateMap = {},
    configModule,
    initModule,
    generateCard,
    onShowMore;
  //----------------- END MODULE SCOPE VARIABLES ---------------

  //------------------- BEGIN UTILITY METHODS ------------------
  //////////////////
  //Generate a card with collapsible middle section with more details
  //
  generateCard = function(obj) {
    var editUrl = "#!/customerEdit/" + obj.id;

    var cardClass = "";
    var urlClass = "";

    //LAPSED
    if (obj.active && obj.lapsed) {
      cardClass = "border-warning text-warning";
      urlClass = "text-warning";
    }

    //ACTIVE
    if (obj.active && !obj.lapsed) {
      cardClass = "border-primary text-primary";
    }

    //INACTIVE
    if (!obj.active) {
      cardClass = "border-primary text-primary";
      urlClass = "text-secondary";
    }

    // var cardClass = obj.active
    //   ? "border-primary text-primary"
    //   : "border-secondary text-secondary";
    // var urlClass = obj.active ? "" : "text-secondary";

    return (
      '<div class="card ' +
      cardClass +
      ' mb-3">' +
      '<h4 class="card-header"><a class="' +
      urlClass +
      '" href=' +
      editUrl +
      ">" +
      obj.name +
      "</a></h4>" +
      '<div class="collapse" id="card-collapse' +
      obj.id +
      '">' +
      '<div id="card-body' +
      obj.id +
      '" class="card-body"/>' +
      "</div>" +
      '<div class="card-footer">' +
      '<button id="btnMore' +
      obj.id +
      '" class="btn btn-outline-dark mdi mdi-basket mdi-24px mr-3" type="button"/>' +
      // '<a href="' + editUrl + '" class="btn btn-outline-success mdi mdi-account-edit mdi-24px "></a>' +
      "</div>" +
      "</div>"
    );
  };
  //-------------------- END UTILITY METHODS -------------------

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

  ////////////////////////////////////////////
  //ONMORE
  //
  onShowMore = function(event) {
    event.preventDefault();

    var customerId = event.data;
    var $cardbody = $("#card-body" + customerId);
    var $collapseDiv = $("#card-collapse" + customerId);

    var isOpen = $collapseDiv.hasClass("show");

    //either way we don't want the old contents hanging around
    $cardbody.empty();

    //Reload the data?
    if (!isOpen) {
      //===================
      //Get sites
      app.api.get("customer/" + customerId + "/activesubforsites", function(
        sites
      ) {
        if (sites.error) {
          $.gevent.publish("app-show-error", sites.msg);
        } else {
          var cardDisplay = '<ul class="list-unstyled">';

          //Iterate the sites
          for (var SitesIndex = 0; SitesIndex < sites.length; SitesIndex++) {
            //append the site name
            cardDisplay +=
              '<li class="font-weight-bold">' + sites[SitesIndex].name + "</li>";

            //append the active subs
            //purchase link for future
            //https://rockfish.ayanova.com/default.htm#!/purchaseEdit/<PURCHASEID>/<SITEID>
            if (sites[SitesIndex].children.length > 0) {
              cardDisplay += '<ul class="mb-2">';
              for (var SitePurchasesIndex = 0; SitePurchasesIndex < sites[SitesIndex].children.length; SitePurchasesIndex++) {
                //<a class="" href="#!/customerEdit/86">Adtech Systems Inc.</a>
                //cardDisplay += "<li>" + sites[SitesIndex].children[SitePurchasesIndex].name + "</li>";
                var PurchaseId=sites[SitesIndex].children[SitePurchasesIndex].id;
                var SiteId=sites[SitesIndex].id;
                var PurchaseUrl='<a href="#!/purchaseEdit/'+PurchaseId+'/'+SiteId+'">' + sites[SitesIndex].children[SitePurchasesIndex].name + '</a>';
                cardDisplay += '<li>'+ PurchaseUrl  + '</li>';
              }
              cardDisplay += "</ul>";
            } else {
              cardDisplay +=
                '<ul class="text-danger"><li>NO ACTIVE SUBS</li></ul>';
            }
          }
          cardDisplay += "</ul>";
          $cardbody.append(cardDisplay);
          //Toggle open after populating the card
          $collapseDiv.collapse("toggle");
        }
      });
      //=========/sites==============
    } else {
      //Toggle closed
      $collapseDiv.collapse("toggle");
    }

    return false;
  };
  //-------------------- 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.customers"]({}));

    //===================
    //Get customers
    app.api.get("customer/list", function(res) {
      if (res.error) {
        $.gevent.publish("app-show-error", res.msg);
      } else {
        var $appListActive = $("#rf-list-active");
        var $appListLapsed = $("#rf-list-lapsed");
        var $appListInActive = $("#rf-list-inactive");

        var activeCount = 0;
        var inactiveCount = 0;
        var lapsedCount = 0;

        $.each(res, function(i, obj) {
          if (obj.active) {
            if (obj.lapsed) {
              lapsedCount++;
              $appListLapsed.append(generateCard(obj));
              $("#btnMore" + obj.id).bind("click", obj.id, onShowMore);
            } else {
              activeCount++;
              $appListActive.append(generateCard(obj));
              $("#btnMore" + obj.id).bind("click", obj.id, onShowMore);
            }
          } else {
            inactiveCount++;
            $appListInActive.append(generateCard(obj));
            $("#btnMore" + obj.id).bind("click", obj.id, onShowMore);
          }
        });

        //Show the count of customers by status
        $("#rf-list-count")
          .empty()
          .append(res.length + " items ");

          $("#rf-active-count-badge").text(activeCount);
          $("#rf-lapsed-count-badge").text(lapsedCount);
          $("#rf-inactive-count-badge").text(inactiveCount);
      }
    });
    //=========/customers==============

    app.nav.contextClear();
    app.nav.contextAddLink("customerEdit/new", "New", "plus");
    app.nav.contextAddLink("search", "Search", "magnify");
  };

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