#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "eps.h"

static void email_content_type(eps_t *, header_t *, void *);

struct i_header_t _i_headers[] = {
  { "Content-type", email_content_type },
  { NULL, NULL }
};

void email_content_type(eps_t *eps, header_t *h, void *x)
{
  char *p = NULL;
  int type = 0, len = 0;

  if ((!eps->h) || (!eps->h->atoms) || (!eps->h->atoms->next) ||
      (!eps->h->atoms->next->data)) {

     type = eps->content_type = CON_TEXT;
     return;
  }

  else {
    if (eps->h_content_type)
       free(eps->h_content_type);

    len = strlen(eps->h->atoms->next->data);

    eps->h_content_type = (char *)malloc(len + 1);
    if (eps->h_content_type) {
       memset(eps->h_content_type, 0, len + 1);
       memcpy(eps->h_content_type, eps->h->atoms->next->data, len);
    }

    type = content_parse(eps->h->atoms->next->data, TYP_CON);
    eps->content_type = type;
  }

  if (type & CON_MULTI) {
     p = header_fetch_atom(eps->h, "boundary");
     if (p) {
        if (eps->b == NULL) {
           eps->b = boundary_alloc();
           if (eps->b == NULL) {
              eps->content_type = CON_TEXT;
              return;
           }
        }

        boundary_add(eps, p);
     }
  }  
}

void email_header_internal(eps_t *eps)
{
  int i = 0;

  if ((!eps->h) || (!(eps->h->name)) || (!(eps->h->data)))
     return;

  for (i = 0; _i_headers[i].name; i++) {
      if (!(strcasecmp(_i_headers[i].name, eps->h->name)))
            _i_headers[i].func(eps, NULL, NULL);
  } 
}
