/* $Cambridge: hermes/src/prayer/cmd/cmd_include.c,v 1.4 2008/09/17 17:20:25 dpc22 Exp $ */
/************************************************
 *    Prayer - a Webmail Interface              *
 ************************************************/

/* Copyright (c) University of Cambridge 2000 - 2008 */
/* See the file NOTICE for conditions of use and distribution. */

#include "prayer_session.h"

static void generate_form(struct session *session)
{
    struct template_vals *tvals = session->template_vals;
    struct request *request = session->request;
    struct buffer *b = request->write_buffer;

    session_seed_template(session, tvals);
    template_expand("include", tvals, b);
    response_html(request, 200);
}


void cmd_include(struct session *session)
{
    struct request *request = session->request;
    struct draft *draft = session->draft;
    char *start, *end;
    unsigned long len;

    if ((request->argc >= 2) && (!strcmp(request->argv[1], "cancel"))) {
        session_redirect(session, request, "compose");
        return;
    }

    if (request->method != POST) {
        generate_form(session);
        return;
    }

    request_decode_post_multipart(request, NIL, &start, &end);
    *end = '\0';

    if (end > start)
        len = (char *) end - (char *) start;
    else
        len = 0;

    if (len < 1) {
	session_alert(session, "Please choose a file to include");
        generate_form(session);
        return;
    }

    session_log(session, "[cmd_include] Included %lu bytes", end - start);

    if (draft->body && draft->body[0])
        draft->body = pool_strcat3(draft->pool, draft->body, CRLF, start);
    else
        draft->body = pool_strdup(draft->pool, start);

    session_redirect(session, request, "compose");
}
