/*

EntityType.cpp

Determies the HTTP content type property given the file extension of the
requested file.  The extension includes the '.' e.g. ".html".

*/

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "logging.h"
#include "EntityType.h"

#define MAX_EXTENSION_LEN 7

#define HTML_EXTENSIONS ".html:.htm:"
#define TEXT_EXTENSIONS ".txt:.java:.c:.cpp:.h:"
#define JPEG_EXTENSIONS ".jpg:.jpeg:"
#define GIF_EXTENSION ".gif"
#define PNG_EXTENSION ".png"
#define BIN_EXTENSIONS ".tar.gz:.gz:.zip:.tar:.tgz:.bz2:.avi:.asf:.mpeg:.mpg:.mov:.mp3:.wav:"


EntityType::EntityType(char* ext)
{
    m_reason[0] = 0;
    m_type[0] = 0;

    if (ext == NULL) {
        strcpy(m_reason, "no file extension");
        return;
    }
    if (strlen(ext) > MAX_EXTENSION_LEN + 1) {
        sprintf(m_reason, "extension too long: %s", ext);
        return;
    }
    char ext_colon[MAX_EXTENSION_LEN+3];
    int i;
    for (i = 0; i < strlen(ext); i++) {
        ext_colon[i] = tolower(ext[i]);
    }
    ext_colon[i] = ':';
    ext_colon[i+1] = 0;
    if (strstr(HTML_EXTENSIONS, ext_colon) > 0) {
        strcpy(m_type, TYPE_TEXT_HTML);
    } else if (strstr(JPEG_EXTENSIONS, ext_colon) > 0) {
        strcpy(m_type, TYPE_IMAGE_JPEG);
    } else if (strcmp(GIF_EXTENSION, ext) == 0) {
        strcpy(m_type, TYPE_IMAGE_GIF);
    } else if (strcmp(PNG_EXTENSION, ext) == 0) {
        strcpy(m_type, TYPE_IMAGE_PNG);
    } else if (strstr(TEXT_EXTENSIONS, ext_colon) > 0) {
        strcpy(m_type, TYPE_TEXT_PLAIN);
    } else if (strstr(BIN_EXTENSIONS, ext_colon) > 0) {
        strcpy(m_type, TYPE_BINARY);
    } else {
        sprintf(m_reason, "invalid extension: %s", ext);
    }
}