/* $Cambridge: hermes/src/prayer/cmd/cmd_filter_mbox.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_filter_mbox(struct session *session)
{
    struct request *request = session->request;
    char *mailbox;
    BOOL copy;

    if (session->half_filter == NIL) {
        session_message(session,
                        "No filter item defined at the current time");
        session_redirect(session, request, "error");
        return;
    }

    if (request->argc != 3) {
        session_redirect(session, request, "error");
        return;
    }

    copy = !strcmp(request->argv[1], "copy") ? T : NIL;
    mailbox = request->argv[2];

    string_canon_decode(mailbox);

    filter_set_mailbox(session->half_filter, mailbox);
    filter_set_copy(session->half_filter, copy);

    account_filter_add(session->account, session->half_filter);

    if (account_mail_update(session->account, request->pool)) {
        FILTER_TYPE type = session->half_filter->type;

        if (type == FILTER_SENDER)
            session_message(session, "Added SENDER filter");
        else if (type == FILTER_RECIPIENT)
            session_message(session, "Added RECIPIENT filter");
        else if (type == FILTER_SUBJECT)
            session_message(session, "Added SUBJECT filter");
        else if (type == FILTER_BLOCK)
            session_message(session, "Added BLOCK filter");
        else
            session_message(session, "Added Unknown filter type?");
    } else {
        char *msg = account_fetch_message(session->account);

        session_message(session, "Problem updating filters: %s", msg);
        session_log(session,
                    "[cmd_filter_mbox()] Problem updating filters: %s", msg);
    }

    /* Remove halfway filter */
    session->half_filter = NIL;

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