/* $Cambridge: hermes/src/prayer/session/stream.c,v 1.3 2008/09/16 09:59:58 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"

/* Helper functions for c-client stream object */

/* Mostly working around ideas that c-client seems to use text strings
 * rather than flag bits to mark messages. May just be limits in my
 * understanding of c-client, but I can't find a better interface to work
 * with at the moment */

/* ====================================================================== */

/* stream_check_uid() ***************************************************
 *
 * Check that msgno and msguid match.
 *  session:
 *   stream:
 *    msgno: Message Number which should contain this UID (bext first guess)
 *   msguid: Message UID that we are looking for
 *
 * Returns: Msgno of message containing this UID (typically msgno unless
 *          an external expunge event has just taken place).
 ***********************************************************************/

unsigned long
stream_check_uid(struct session *session,
                 MAILSTREAM * stream,
                 unsigned long msgno, unsigned long msguid)
{
    if ((msgno == 0) || (msguid == 0)) {
        session_message(session, "Reference to illegal Message UID 0");
        session_log(session,
                    "[stream_check_uid] Reference to illegal Message UID 0");
        return (0);
    }

    /* Could just do reverse lookup (msguid -> msgno).  This way is a bit
     * more efficient as don't have to scan the entire index looking for a
     * particular UID most of the time */

    if ((msgno > stream->nmsgs)
        || (ml_uid(session, stream, msgno) != msguid)) {
        /* Messages have moved: external expunge event */
        if (((msgno = ml_msgno(session, stream, msguid)) == 0) ||
            (msgno > stream->nmsgs)) {
            /* Couldn't find this UID in folder */
            session_message(session, "Message UID %lu has been expunged",
                            msguid);
            return (0);
        }
    }
    return (msgno);
}

/* stream_find_unread() **************************************************
 *
 * Find first unread message in stream.
 ************************************************************************/

unsigned long
stream_find_unread(struct session *session, MAILSTREAM * stream)
{
    unsigned long msgno;
    char seq[64];

    if (stream->nmsgs == 0)
        return (0);

    sprintf(seq, "1:%lu", stream->nmsgs);
    ml_fetch_fast(session, stream, seq, 0);

    /* Record last unread message from inbox */
    for (msgno = 1; msgno <= stream->nmsgs; msgno++) {
        if (!mail_elt(stream, msgno)->seen)
            return (msgno);
    }

    return (0);
}
