/* $Cambridge: hermes/src/prayer/cmd/cmd_forward.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"

#include "cmd.h"

void cmd_forward(struct session *session)
{
    struct template_vals *tvals = session->template_vals;
    struct request *request = session->request;
    struct options *options = session->options;
    struct prefs *prefs = options->prefs;
    struct buffer *b = request->write_buffer;
    MAILSTREAM *stream = session->stream;
    struct list_item *li;
    unsigned long count, msgno, msguid;

    if ((request->argc > 1) && !strcmp(request->argv[1], "aggregate")) {
        if (prefs->use_mark_persist)
            count = msgmap_marked_count(session->zm);
        else
            count = msgmap_tmp_marked_count(session->zm);

        if (count > 1)
            session_message(session, "Forwarding %lu marked messages",
                            count);
        else if (count == 1)
            session_message(session, "Forwarding single marked message");
        else {
            session_message(session, "No marked messages to forward");
            session_redirect(session, request, "list");
            return;
        }
        session->aggregate = T;
    } else if (request->argc > 1) {
        if (request->argc < 3) {
            session_redirect(session, request, "error");
            return;
        }
        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;
        }

        session->aggregate = NIL;
        session->current = atoi(request->argv[1]);
        session_message(session, "Forwarding message %lu",
                        session->current);
    }

    if (list_length(options->role_list) == 0L) {
        cmd_forward1(session);
        return;
    }

    count = 0;
    template_vals_foreach_init(tvals, "@roles", count);
    template_vals_foreach_string(tvals, "@roles", count, "name", "default");
    count++;

    for (li = options->role_list->head; li; li = li->next) {
        struct role *role = (struct role *) li;

        template_vals_foreach_init(tvals, "@roles", count);
        template_vals_foreach_string(tvals, "@roles", count,
                                     "name", role->name);
        count++;
    }

    template_vals_string(tvals, "next", "forward1");
    session_seed_template(session, tvals);
    template_expand("roles_select", tvals, b);
    response_html(request, 200);
}
