/* $Cambridge: hermes/src/prayer/cmd/cmd_mark.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_mark(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->nmsgs - zm->marked;

        msgmap_mark_all(zm);
        if (count != 1)
            session_message(session, "Marked %lu messages", count);
        else
            session_message(session, "Marked 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", ST_SET)) {
            session_message(session,
                            "Failed to mark message %lu as read: %s",
                            msgno, ml_errmsg());
            session_log(session,
                        "[cmd_mark] Failed to mark message number %lu as read: %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_mark(session->zm, msgno))
            session_message(session, "Marked message %lu", msgno);
        else
            session_message(session, "Message %lu already marked", msgno);
    }

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