/* $Cambridge: hermes/src/prayer/cmd/cmd_disp_unmark.c,v 1.2 2008/05/19 15:55:54 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_unmark(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_unmark(zm, msgno))
            session_message(session,
                            "Unmarked message %lu, displaying %lu out of %lu",
                            msgno, next, zm->nmsgs);
        else
            session_message(session,
                            ("Message %lu already unmarked, "
                             "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_unmark(zm, msgno))
            session_message(session,
                            "Unmarked message %lu, no more messages",
                            msgno);
        else
            session_message(session,
                            "Message %lu already unmarked, no more messages",
                            msgno);

        session->current = msgno;
        session_redirect(session, request, "list");
    }
}
