#include "IMFMessage.h"
#include "IMFHeader.h"
#include "IMFMultipart.h"
#include "IMFPlainText.h"
#include "Log.h"

namespace coreutils {

   IMFMessage::IMFMessage() : ZString() {}

   IMFMessage::IMFMessage(ZString &in) : ZString(in) {

      while (!in.ifNext("\r\n"))
   	  headers.emplace_back(in);

      ZString type = getHeader("Content-Type");

      int len = getHeader("Content-Length").asInteger();
      if(len > 0) {
         block = in.readBlock(len);
         if(type.equals("multipart/form-data")) {
            ZString boundary(getHeaderKeyPairValue("Content-Type", "boundary"));
   	      multipart = IMFMultipart(block, boundary);
         }
      }
   }

   IMFMessage::~IMFMessage() {}

   void IMFMessage::output(std::stringstream &out) {
//      for(IMFHeader header: headers) {
//         out << header.getKey() << ": " << header.getValue() << "\r\n";
//      }
      out << newHeaders.str() << "\r\n";
   }

   void IMFMessage::addHeader(IMFHeader header) {
      std::stringstream out;
      header.output(out);
      newHeaders << out.str() ;
   }

   ZString IMFMessage::getHeader(ZString key, bool valueOnly) {
      for(IMFHeader header: headers) {
         if(header.getKey().equals(key)) {
	         ZString value = header.getValue();
	         if(valueOnly) {
	            std::vector<ZString> split = ZString(value).split(";");
	            value = split[0];
	         }
      	   return value;
         }
      }
      return ZString();
   }

   ZString IMFMessage::getHeaderKeyPairValue(const char *headerKey, const char *key) {
      return getHeaderKeyPairValue(ZString(headerKey), ZString(key));
   }

   ZString IMFMessage::getHeaderKeyPairValue(ZString headerKey, ZString key) {
      ZString value;
      ZString psource(getHeader(headerKey, false));
      for(ZString work: psource.split(";")) {
         work.skipWhitespace();
         ZString token = work.getTokenExclude("=");
         if(work.ifNext("=")) {
            if(token.equals(key)) {
               if(work.ifNext("\"")) 
                 value = work.getTokenExclude("\"");
               else 
                 value = work;               
               return value;
            }
            else
              continue;
         } else if (work.ifNext(";") || work.ifNext(" ")) {
            if(token.equals(key))
              return ZString("true");
            else
              continue;
         }
      }
      return ZString();
   }

}
