/* $Cambridge: hermes/src/prayer/cmd/cmd_unmark.c,v 1.4 2008/09/17 17:20:25 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_unmark(struct session *session)
{
    struct request *request = session->request;
    MAILSTREAM *stream = session->stream;

    if ((request->argc == 2) && (!strcmp(request->argv[1], "all"))) {
        struct msgmap *zm = session->zm;
        unsigned long count = zm->marked;

        msgmap_unmark_all(zm);
        if (count != 1)
            session_message(session, "Unmarked %lu messages", count);
        else
            session_message(session, "Unmarked 1 message");
    } else if ((request->argc == 4) && (!strcmp(request->argv[1], "read"))) {
        unsigned long msgno = atoi(request->argv[2]);
        unsigned long msguid = atoi(request->argv[3]);

        if (!(msgno = stream_check_uid(session, stream, msgno, msguid))) {
            session_redirect(session, request, "restart");
            return;
        }
        session->current = msgno;
        if (!ml_flag(session, stream, string_itoa_tmp(msgno), "\\SEEN", 0)) {
            session_alert(session,
                          "Failed to mark message %lu as unread: %s",
                          msgno, ml_errmsg());
            session_log(session,
                        ("[cmd_unmark] "
                         "Failed to mark message number %lu as unread: %s"),
                        msgno, ml_errmsg());
            session_redirect(session, request, "restart");
            return;
        }
        session_message(session, "Marked message %lu as read", msgno);
    } else if (request->argc == 3) {
        unsigned long msgno = atoi(request->argv[1]);
        unsigned long msguid = atoi(request->argv[2]);

        if (!(msgno = stream_check_uid(session, stream, msgno, msguid))) {
            session_redirect(session, request, "restart");
            return;
        }

        if (msgmap_unmark(session->zm, msgno))
            session_message(session, "Unmarked message %lu", msgno);
        else
            session_message(session, "Message %lu already unmarked",
                            msgno);
    }

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