/* $Cambridge: hermes/src/prayer/cmd/cmd_vaclog.c,v 1.3 2008/09/16 09:59:55 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_error(struct session *session)
{
    struct template_vals *tvals = session->template_vals;
    struct account *account = session->account;
    struct request *request = session->request;
    char *msg = account_fetch_message(account);
    struct buffer *b = request->write_buffer;

    if (!(msg && msg[0]))
        msg = "Unable to check mail processing status";

    template_vals_string(tvals, "msg", msg);
    session_seed_template(session, tvals);
    template_expand("vaclog_fail", tvals, b);
    response_html(request, 200);
}

void cmd_vaclog(struct session *session)
{
    struct template_vals *tvals = session->template_vals;
    struct account *account = session->account;
    struct request *request = session->request;
    struct buffer *b = request->write_buffer;
    char *vaclog;

    if (request->method == POST) {
        request_decode_form(request);

        if (assoc_lookup(request->form, "sub_clear")) {
            if (account_vaclog_clear(session->account, request->pool)) {
                session_message(session, "Cleared vacation log");
            } else {
                char *msg = account_fetch_message(session->account);

                session_message(session,
                                "Failed to clear vacation log: %s", msg);
                session_log(session,
                            "[cmd_vaclog] Failed to clear vacation log: %s",
                            msg);
            }
        }
        session_redirect(session, request, "manage");
        return;
    }

    if (!(vaclog = account_vaclog_fetch(account, request->pool))) {
        generate_error(session);
        return;
    }

    template_vals_string(tvals, "vaclog", vaclog);
    session_seed_template(session, tvals);
    template_expand("vaclog", tvals, b);
    response_html(request, 200);        /* Success */
}
