/* $Cambridge: hermes/src/prayer/cmd/cmd_change.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_change(struct session *session)
{
    struct request *request = session->request;
    char *name;

    if (request->method == POST) {
        request_decode_form(request);

        if (!(name = utf8_to_imaputf7(request->pool, assoc_lookup(request->form, "folder")))) {
            session_redirect(session, request, "error");
            return;
        }
        string_canon_decode(name);
    } else if (request->argc < 2) {
        session_redirect(session, request, "error");
        return;
    } else {
        name = pool_strdup(session->pool, request->argv[1]);
        string_canon_decode(name);
    }

    if (!session_streams_change(session, name)) {
        session_message(session, "Unable to switch to folder: %s",
                        utf8_from_imaputf7(request->pool, name));
        session_redirect(session, request, "restart");
        return;
    }

    if (!strcasecmp(name, "inbox")) {
        unsigned long msgno = stream_find_unread(session, session->stream);

        if (msgno > 0) {
            session->current = msgno;
            session->last_displayed = msgno;
            session_message(session, "First unread message: %lu", msgno);
        } else
            session_message(session, "No unread messages in inbox");
    }

    session_message(session, "Switched to mailbox: %s",
                    utf8_from_imaputf7(request->pool, session->foldername));
    session_log(session, "[cmd_change] Switched to mailbox: %s",
                session->foldername);

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