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

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

  ///////////////////////////////////
  // SEND A REPLY OR NEW MESSAGE
  //
  onSend = function(event) {
    event.preventDefault();

    $.gevent.publish("app-clear-error");

    //get form data
    var formData = $("form").serializeArray({
      checkboxesAsBools: true
    });

    //var submitData = {composition:$("#composition").val()};
    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.create(
        "mail/reply/" +
          stateMap.context.params.mail_account +
          "/" +
          stateMap.context.params.mail_id,
        submitData,
        function(res) {
          if (res.error) {
            $.gevent.publish("app-show-error", res.msg);
          } else {
            page("#!/inbox");
          }
        }
      );
    } else {
      alert("STUB: New message composition not implemented yet");
      // //it's a new record - create
      // app.api.create('customer', submitData, function (res) {
      //     if (res.error) {
      //         $.gevent.publish('app-show-error',res.msg);
      //     } else {
      //         page('#!/inbox');
      //     }
      // });
    }

    return false;
  };

  ///////////////////////////////////
  // SPAM HANDLER
  //
  onSpam = function(event) {
    event.preventDefault();

    $.gevent.publish("app-clear-error");
    
    //is this a new record?
    if (stateMap.id == "new") {
      alert("New message spam handling makes no sense - figure it out!");
      return false;
    }

    app.api.create(
      "mail/isspam/" +
        stateMap.context.params.mail_account +
        "/" +
        stateMap.context.params.mail_id,
      null,
      function(res) {
        if (res.error) {
          $.gevent.publish("app-show-error", res.msg);
        } else {
          page("#!/inbox");
        }
      }
    );

    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.mailEdit"]({}));
    // stateMap.replyMode = false;
    // if (stateMap.context.querystring.endsWith('reply')) {
    //     stateMap.replyMode = true;
    // }

    app.nav.contextClear();
    app.nav.contextAddLink("inbox/", "Inbox", "inbox");

    //id should always have a value, either a record id or the keyword 'new' for making a new object
    if (stateMap.id != "new") {
      //fetch existing record
      app.api.get(
        "mail/preview/" +
          stateMap.context.params.mail_account +
          "/" +
          stateMap.context.params.mail_folder +
          "/" +
          stateMap.context.params.mail_id,
        function(res) {
          if (res.error) {
            // app.nav.contextClear();
            // app.nav.contextAddLink("inbox/", "Inbox", "inbox");
            $.gevent.publish("app-show-error", res.msg);
          } else {
            //fill out form
            // app.nav.contextClear();
            //app.nav.contextAddLink("inbox/", "Inbox", "inbox");
            $("#message").text(res.preview);
            if (res.isKeyRequest) {
              app.nav.contextAddLink(
                "licenseRequestEdit/" + res.id,
                "Make",
                "key"
              );
            } else {
              $("#composition").text("\n\n- John\nwww.ayanova.com");
            }
          }
        }
      );

      $("#btn-send").bind("click", onSend);

      //Context menu
      app.nav.contextAddButton("btn-generate", "IsSpam", "axe", onSpam);
    } else {
      //NEW email options
      var $group = $("#sendToGroup");
      $group.removeClass("invisible");

      // app.nav.contextClear();
      // app.nav.contextAddLink("inbox/", "Inbox", "inbox");
      // app.nav.contextAddButton('btn-send', 'Send', 'send', onSend);
    }
  };

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