/* $Cambridge: hermes/src/prayer/cmd/cmd_expunge1.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_expunge1(struct session *session)
{
    struct request *request = session->request;
    MAILSTREAM *stream = session->stream;
    struct msgmap *zm = session->zm;
    unsigned long count;
    unsigned long offset, msgno;
    unsigned long msguid_current;
    MESSAGECACHE *elt;

    /* Make sure msgmap is up to date before we start */
    if (!msgmap_update(zm)) {
        session_alert(session, "Failed to update msgmap");
        session_redirect(session, request, "restart");
        return;
    }

    /* Count deleted messages in folder */
    for (count = 0, msgno = 1; msgno <= stream->nmsgs; msgno++) {
        if (!(elt = ml_elt(session, stream, msgno))) {
            session_redirect(session, request, "restart");
            return;
        }
        if (elt->deleted)
            count++;
    }

    if (session->current > 0) {
        /* Find "closest" undeleted message to current in map */
        offset = msgmap_find_undeleted(session->zm, session->current);
        session->current = msgmap_value(session->zm, offset);
    }

    /* Record UID of this message so that we can find it after expunge */
    if (session->current > 0)
        msguid_current = ml_uid(session, stream, session->current);
    else
        msguid_current = 0;

    if (!ml_expunge(session, stream)) {
        session_redirect(session, request, "restart");
        return;
    }

    if (stream == session->inbox_stream)
        session->inbox_last_ping_time = time(NIL);
    else if (stream == session->draft_stream)
        session->draft_last_ping_time = time(NIL);
    else
        session->other_last_ping_time = time(NIL);

    /* Update msgmap (recalculates marked message count) */
    if (!msgmap_update(zm)) {
        session_alert(session, "Failed to update msgmap");
        session_redirect(session, request, "restart");
        return;
    }

    /* Current message has probably moved */
    if (msguid_current > 0)
        session->current = ml_msgno(session, stream, msguid_current);
    else
        session->current = zm->nmsgs;

    session_log(session, "[cmd_expunge1] Expunged %lu message(s) from %s",
                count, session->foldername);

    if (count > 1)
        session_message(session, "Expunged %lu messages", count);
    else if (count == 1)
        session_message(session, "Expunged 1 message");
    else
        session_message(session, "No messages to expunge");

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