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

void cmd_disp_mark(struct session *session)
{
    struct msgmap *zm = session->zm;
    struct request *request = session->request;
    struct pool *pool = request->pool;
    MAILSTREAM *stream = session->stream;
    unsigned long msgno, msguid;
    char *s;
    unsigned long zm_offset;

    if (request->argc < 2) {
        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, "restart");
        return;
    }

    /* Find next message in msgmap */
    if (!msgmap_update(zm)) {
        session_redirect(session, request, "restart");
        return;
    }


    zm_offset = msgmap_find(zm, msgno);
    if (zm_offset < msgmap_size(zm)) {
        unsigned long next = msgmap_value(zm, zm_offset + 1);

        if (msgmap_mark(zm, msgno))
            session_message(session,
                            "Marked message %lu, displaying %lu out of %lu",
                            msgno, next, zm->nmsgs);
        else
            session_message(session,
                            "Message %lu already marked, displaying %lu out of %lu",
                            msgno, next, zm->nmsgs);

        s = pool_printf(pool, "display/%lu/%lu",
                        next, ml_uid(session, stream, next));
        session_redirect(session, request, s);
    } else {
        if (msgmap_mark(zm, msgno))
            session_message(session,
                            "Marked message %lu, no more messages", msgno);
        else
            session_message(session,
                            "Message %lu already marked, no more messages",
                            msgno);
        session->current = msgno;
        session_redirect(session, request, "list");
    }
}
