/* $Cambridge: hermes/src/prayer/cmd/cmd_printable.c,v 1.10 2010/07/08 16:55:49 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"

void cmd_printable(struct session *session)
{
    struct template_vals *tvals = session->template_vals;
    struct options *options = session->options;
    struct prefs *prefs = options->prefs;
    struct request *request = session->request;
    struct msgmap *zm = session->zm;
    unsigned long msgno, msguid;
    char *section;
    struct buffer *b = request->write_buffer;
    MAILSTREAM *stream = session->stream;
    BOOL html_show_images = prefs->html_remote_images;

    if (!msgmap_update(zm)) {
        session_alert(session, "Failed to update msgmap");
        session_redirect(session, request, "restart");
        return;
    }

    if (msgmap_size(zm) == 0) {
        session_message(session, "Folder is empty");
        session_redirect(session, request, "list");
        return;
    }

    /* Save options if anything changed */
    if (options->save)
        session_streams_save_options(session);

    /* Record last command for compose/cancel and friends */
    if (!session->draft->have_draft)
        session->compose_parent_cmd = "display";

    /* Record last command for save/cancel */
    session->copy_parent_cmd = "display";

    /* Record last command for addressbook take */
    session->take_parent_cmd = "display";

    if ((request->argc == 5) && !strcmp(request->argv[4], "show_images"))
        html_show_images = T;

    section = NIL;
    if (request->argc >= 4)
        section = request->argv[3];

    if (request->argc >= 3) {
        msgno = atoi(request->argv[1]);
        msguid = atoi(request->argv[2]);

        if (!(msgno = stream_check_uid(session, stream, msgno, msguid))) {
            session_redirect(session, request, "list");
            return;
        }
    } else {
        msgno = session->last_displayed;

        if ((msgno == 0) || (msgno > msgmap_size(zm)))
            msgno = msgmap_value(zm, msgmap_size(zm));

        msguid = ml_uid(session, stream, msgno);
    }

    session->current = msgno;
    session->last_displayed = msgno;

    display_addnav(session, stream, msgno);
    display_addhdrs(session, stream, msgno);

    session_seed_template(session, tvals);
    template_expand("printable", tvals, b);

    if (!display_body(session, request, stream, msgno, section,
                      "printable", html_show_images)) {
        session_redirect(session, request, "restart");
        return;
    }

    template_expand("printable_tail", tvals, b);
    /* Send out the response */
    response_html(request, 200);
}
