#import "MIMEMail.h"
#import "FileName.h"
#import "support.h"
#include <sys/file.h>

#define MIME_VERSION "MIME-Version: 1.0\n"
#define MAJOR_CONTENT_TYPE "Content-Type: multipart/mixed; boundary="
#define TEXT_CONTENT_TYPE "Content-Type: TEXT/plain; CHARSET=US-ASCII\n"
#define SUB_CONTENT_TYPE "Content-Type: APPLICATION/octet-stream; name =\"%s\"\nContent-Transfer-Encoding: BASE64\n\n"
#define BOUNDRY "\n--MailEnclosure-Boundry--------MailEnclosure-Boundry"

@implementation MIMEMail

- buildEnvelope
{
   [super buildEnvelope];
   fwrite(MIME_VERSION, 1, strlen(MIME_VERSION), fp);
   fwrite(MAJOR_CONTENT_TYPE, 1, strlen(MAJOR_CONTENT_TYPE), fp);
   putc('"',fp);
   fwrite(BOUNDRY + 3, 1, strlen(BOUNDRY + 3), fp);
   putc('"',fp);
   putc('\n',fp);
   return self;
}

- buildBody
{
   id aFile;
   int cnt, x;
   int blen = strlen(BOUNDRY);

   if(strlen([text stringValue]))
   {
      fwrite(BOUNDRY,1,blen,fp);
      putc('\n',fp);
      fwrite(TEXT_CONTENT_TYPE,1,strlen(TEXT_CONTENT_TYPE),fp);
      fwrite([text stringValue], 1, strlen([text stringValue]),fp);
   }
   
   for(x = 0, cnt = [attachments count]; x < cnt; x++)
   {
      aFile = [attachments objectAt: x];
      fwrite(BOUNDRY,1,blen,fp);
      putc('\n',fp);
      fprintf(fp,SUB_CONTENT_TYPE, [aFile basename]);
      base64([aFile stringValue], fp);
   }
   
   fwrite(BOUNDRY,1,blen,fp);
   fwrite("--\n",1,3,fp);
   return self;
}

-(BOOL)supportsAttachments
{
   return YES;
}

@end
