/* $Cambridge: hermes/src/prayer/cmd/cmd_welcome.c,v 1.5 2008/10/31 10:55:19 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_welcome_page(struct session *session)
{
    struct template_vals *tvals = session->template_vals;
    struct pool *pool = tvals->pool;
    struct config *config = session->config;
    struct request *request = session->request;
    struct buffer *b = request->write_buffer;
    char *s;
    unsigned long hours = config->session_timeout / (60 * 60);
    unsigned long mins = (config->session_timeout / 60) % 60;

    if ((hours > 1) && (mins > 1))
        s = pool_printf(pool, "%lu hours and %lu minutes", hours, mins);
    else if ((hours > 1) && (mins == 1))
        s = pool_printf(pool, "%lu hours and 1 minutes", hours);
    else if (hours > 1)
        s = pool_printf(pool, "%lu hours", hours);
    else if (hours == 1)
        s = "1 hour";
    else
        s = pool_printf(pool, "%lu minutes", mins);

    template_vals_string(tvals, "timeout", s);
    session_seed_template(session, tvals);
    template_expand("welcome", tvals, b);
    response_html(request, 200);
}

void cmd_welcome(struct session *session)
{
    struct options *options = session->options;
    struct prefs *prefs = options->prefs;
    struct request *request = session->request;
    unsigned long msgno;

    if ((request->method != POST) && (prefs->use_welcome)) {
        generate_welcome_page(session);
        return;
    }

    if (request->method == POST) {
        request_decode_form(request);
        if (!assoc_lookup(request->form, "enable_welcome")) {
            options->prefs->use_welcome = NIL;
            options->prefs_save->use_welcome = NIL;
            session->options->save = T;
        }
    }

    msgno = stream_find_unread(session, session->stream);

    if (msgno > 0) {
        if (prefs->use_unread) {
            session->current = msgno;
            session->last_displayed = msgno;
        }
        session_message(session, "First unread message: %lu", msgno);
    } else
        session_message(session, "No unread messages in inbox");

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