#include "MailDelivery.h"
#include "Directory.h"
#include "time.h"

namespace mail {
   
   MailDelivery::MailDelivery(core::EPoll &ePoll, std::string mailQueue) : INotify(ePoll) {
      addWatch(mailQueue);   
      startDelivery(mailQueue);
   }

   void MailDelivery::onDataReceived(std::string data) {
      
      // TODO: Receive file and parse email name.
 
      // TODO: Compare time to named time and if time has passed then send the message
      // TODO:  If email is a local mailbox then make a hard link to the mail message in the appropriate Inbox. Remove entry from queue.
      // TODO:  If email is a remote mailbox then perform remote send algorithm.
      // TODO:   If error sending on remote then calculate next send attempt time and rename file to reflect new time.
      // TODO: If date is on the future then set a timer to that time and wait.
            
   }
   
   int MailDelivery::startDelivery(std::string mailQueue) {
      coreutils::Directory mailDir(mailQueue);
      std::string entryName = mailDir.get().getName();      
      std::string now = getMailFileName();
//      if(now > entryName) {
//	 std::string recipientName = coreutils::File(); //  read recipient name
//	 if(isLocal(recipientName)) {
//	    link(existing, new);
//	 } else {	       
	    //   open connect socket to mx.domain
	    //   if error 
	    //    calculate future date name and rename mail data
	    //   else 
	    //    write smtp data on socket 25
	    // 
//	 }
  //    }      
   }
   
   int MailDelivery::deliver() {
   
   
   }

   std::string MailDelivery::getMailFileName() {
      char fileName[64];
      time_t gtime;
      time(&gtime);
      struct tm *timex;
      timex = gmtime(&gtime);
      strftime(fileName, 64, "%Y%m%d%H%M%S", gmtime(&gtime));
      return std::string(fileName);   
   }
      
}
