/**
 * The intent of this file is to test that movemail download code
 * works correctly.
 */
Components.utils.import("resource:///modules/mailServices.js");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/Task.jsm");
Components.utils.import("resource://testing-common/mailnews/PromiseTestUtils.jsm");

var testSubjects = ["[Bug 397009] A filter will let me tag, but not untag",
                    "Hello, did you receive my bugmail?",
                    "[Bug 655578] list-id filter broken"];

var gMsgHdrs = [];
var gHdrIndex = 0;

// the movemail spool dir file is these three files
// concatenated together.

let gFiles = ["../../../data/bugmail1",
              "../../../data/draft1",
              "../../../data/bugmail19"];

var gMoveMailInbox;

function run_test()
{
  localAccountUtils.loadLocalMailAccount();
  
  let incoming = MailServices.accounts.createIncomingServer("", "", "movemail");
  let workingDir = Services.dirsvc.get("CurWorkD", Ci.nsIFile);
  let workingDirFile = workingDir.clone();
  let fullPath = workingDirFile.path + "/data/movemailspool";
  workingDirFile.initWithPath(fullPath);
  // movemail truncates spool file, so make a copy, and use that
  workingDirFile.copyTo(null, "movemailspool-copy");
  fullPath += "-copy";
  dump("full path = " + fullPath + "\n");
  incoming.setCharValue("spoolDir", fullPath);
  incoming.QueryInterface(Ci.nsILocalMailIncomingServer);
  incoming.getNewMail(null, null, null);
  gMoveMailInbox = incoming.rootFolder.getChildNamed("INBOX");
  // add 3 messages
  run_next_test();
}

add_task(function continueTest() {
  // get message headers for the inbox folder
  let enumerator = gMoveMailInbox.msgDatabase.EnumerateMessages();
  var msgCount = 0;
  let hdr;
  while (enumerator.hasMoreElements())
  {
    let hdr = enumerator.getNext().QueryInterface(Ci.nsIMsgDBHdr);
    gMsgHdrs.push(hdr);
    do_check_eq(hdr.subject, testSubjects[msgCount++]);
  }
  do_check_eq(msgCount, 3);
});

add_task(function *streamMessages() {
  for (let msgHdr of gMsgHdrs)
    yield streamNextMessage(msgHdr);
});

let streamNextMessage = Task.async(function* (aMsgHdr) {
  let messenger = Cc["@mozilla.org/messenger;1"].createInstance(Ci.nsIMessenger);
  let msgURI = aMsgHdr.folder.getUriForMsg(aMsgHdr);
  dump("streaming msg " + msgURI + " store token = " +
       aMsgHdr.getStringProperty("storeToken"));
  let msgServ = messenger.messageServiceFromURI(msgURI);
  let streamListener = new PromiseTestUtils.PromiseStreamListener();
  msgServ.streamMessage(msgURI, streamListener, null, null, false, "", true);
  let data = yield streamListener.promise;
  do_check_true(data.startsWith("From "));
});

