/*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.purchaseEdit = (function() {
  "use strict";
  //---------------- BEGIN MODULE SCOPE VARIABLES --------------
  var stateMap = {},
    onSave,
    onDelete,
    onRenew,
    configModule,
    initModule,
    onPasteNotes;
  //----------------- END MODULE SCOPE VARIABLES ---------------

  //------------------- BEGIN UTILITY METHODS ------------------
  //-------------------- END UTILITY METHODS -------------------

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

  onSave = function(event) {
    event.preventDefault();
    $.gevent.publish("app-clear-error");
    //get form data
    var formData = $("form").serializeArray({
      checkboxesAsBools: true
    });

    var submitData = app.utilB.objectifyFormDataArray(formData);

    //is this a new record?
    if (stateMap.id != "new") {
      //put id into the form data
      submitData.id = stateMap.id;

      app.api.update("purchase", submitData, function(res) {
        if (res.error) {
          $.gevent.publish("app-show-error", res.msg);
        }
      });
    } else {
      //create new record
      app.api.create("purchase", submitData, function(res) {
        if (res.error) {
          $.gevent.publish("app-show-error", res.msg);
        } else {
          page(
            "#!/purchaseEdit/" + res.id + "/" + stateMap.context.params.site_id
          );
          return false;
        }
      });
    }
    return false; //prevent default
  };

  onRenew = function(event) {
    event.preventDefault();
    $.gevent.publish("app-clear-error");

    if (stateMap.id == "new") {
      $.gevent.publish(
        "app-show-error",
        "Save this record before attempting to renew it"
      );
      return false;
    }
    stateMap.id = "new";

    //case 3396, no more renewal or dupe names
    // var nm = $('#name').val();
    // nm = "DUPE-" + nm;
    // $('#name').val(nm);

    //case 3396, set values accordingly

    //Clear salesOrderNumber
    $("#salesOrderNumber").val("");

    //set purchaseDate to today
    $("#purchaseDate").val(
      moment()
        .toISOString()
        .substring(0, 10)
    );

    //set expireDate to plus one year from today
    $("#expireDate").val(
      moment()
        .add(1, "years")
        .toISOString()
        .substring(0, 10)
    );

    //clear the couponCode
    $("#couponCode").val("");

    //clear the notes
    $("#notes").val("");

    $("#renewNoticeSent").prop("checked", false);
    $("#cancelDate").val("");

    return false; //prevent default
  };

  //ONDELETE
  //
  onDelete = function(event) {
    event.preventDefault();
    $.gevent.publish("app-clear-error");

    var r = confirm("Are you sure you want to delete this record?");
    if (r == true) {
      //====  DELETE  ====
      app.api.remove("purchase/" + stateMap.id, function(res) {
        if (res.error) {
          $.gevent.publish("app-show-error", res.msg);
        } else {
          //deleted, return to master list
          page("#!/purchases/" + stateMap.context.params.site_id);
          return false;
        }
      });
    } else {
      return false;
    }
    return false; //prevent default?
  };

  onPasteNotes = function(event) {
    var clipboardData, pastedData;
    var e = event.originalEvent;

    // // Stop data actually being pasted into div
    // e.stopPropagation();
    // e.preventDefault();

    // Get pasted data via clipboard API
    clipboardData = e.clipboardData || window.clipboardData;
    pastedData = clipboardData.getData("Text");

    //Iterate through the lines looking for the SHareIt name=value lines (they all contain equal signs)
    var lines = pastedData.split("\n"); // lines is an array of strings
    var purchaseData = {};

    // Loop through all lines
    for (var j = 0; j < lines.length; j++) {
      var thisLine = lines[j];
      if (thisLine.includes("=")) {
        var thisElement = thisLine.split("=");
        purchaseData[thisElement[0].trim()] = thisElement[1].trim();
      }
    }

    //Now have an object with the value pairs in it
    if (purchaseData["ShareIt Ref #"]) {
      $("#salesOrderNumber").val(purchaseData["ShareIt Ref #"]);
    }

    // if (purchaseData["E-Mail"]) {
    //   $("#email").val(purchaseData["E-Mail"]);
    // }
  };

  //-------------------- 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.purchaseEdit"]({}));
    var title = "Purchase";

    if (!stateMap.context.params.site_id) {
      throw "app.purchaseEdit.js::initModule - There is no stateMap.context.params.site_id!";
    }

    //Append master record id as a hidden form field for referential integrity
    $("<input />")
      .attr("type", "hidden")
      .attr("name", "siteId")
      .attr("value", stateMap.context.params.site_id)
      .appendTo("#frm");

    //fetch entire site record to get name *and* customer id which is required for redundancy

    //RFC - get site name and customer name for form

    app.api.get("site/" + stateMap.context.params.site_id, function(res) {
      if (res.error) {
        $.gevent.publish("app-show-error", res.msg);
      } else {
        //Also append customer ID redundantly
        $("<input />")
          .attr("type", "hidden")
          .attr("name", "customerId")
          .attr("value", res.customerId)
          .appendTo("#frm");

        title = "Purchase - " + res.name;
        if (stateMap.id != "new") {
          //fetch existing record
          app.api.get("purchase/" + stateMap.id, function(res) {
            if (res.error) {
              $.gevent.publish("app-show-error", res.msg);
            } else {
              //fill out form
              app.utilB.formData(res);
            }
          });
        } else {
          //it's a new record, set default
          $("#purchaseDate").val(new Date().toISOString().substring(0, 10));
        }
        //set title
        //app.nav.setContextTitle(title);
      }
    });

    //Context menu
    app.nav.contextClear();
    app.nav.contextAddLink(
      "purchases/" + stateMap.context.params.site_id,
      "Purchases",
      "basket"
    );

    // bind actions
    $("#btn-save").bind("click", onSave);
    $("#btn-delete").bind("click", onDelete);
    $("#btn-renew").bind("click", onRenew);
    $("#notes").bind("paste", onPasteNotes);

    //Autocomplete
    app.utilB.autoComplete("name", "purchase.name");
    app.utilB.autoComplete("productCode", "purchase.productCode");
    app.utilB.autoComplete("vendorName", "purchase.vendorName");
  };

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