/* $Cambridge: hermes/src/prayer/cmd/cmd_rm1.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_rm1(struct session *session)
{
    struct request *request = session->request;
    struct options *options = session->options;
    struct favourite_list *fl = options->favourite_list;
    MAILSTREAM *stream;
    char *mailbox;

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

    mailbox = string_canon_decode(request->argv[2]);

    if (!strcasecmp(mailbox, "INBOX")) {
        session_alert(session, "Unable to delete inbox folder");
        session_redirect(session, request, "folders");
        return;
    }

    if (session->foldername && session->other_foldername &&
        !strcmp(session->foldername, session->other_foldername) &&
        !strcmp(session->foldername, mailbox)) {

        /* Attempt to delete current mailbox other than INBOX */
        /* Switch to inbox, shut down other stream */
        session_streams_change(session, "INBOX");

        ml_close(session, session->other_stream);
        session->other_stream = NIL;
    }
    stream = session->stream;

    ml_clear_error();
    ml_clear_have_close();

    if (!strcmp(request->argv[1], "directory")) {
        ml_delete(session, stream,
                  session_dir(session, request->pool, mailbox));
        if (ml_have_close()) {
            session_redirect(session, request, "restart");
            return;
        } else if (ml_have_error()) {
            session_alert(session, "%s", ml_errmsg());        /* Includes name */
        } else {
            session_message(session, "Deleted directory: \"%s\"", mailbox);
            folderlist_delete(session->folderlist, mailbox);
        }
    } else {
        ml_delete(session, stream,
                  session_mailbox(session, request->pool, mailbox));

        if (ml_have_close()) {
            session_redirect(session, request, "restart");
            return;
        } else if (ml_have_error()) {
            session_message(session, "%s", ml_errmsg());        /* Includes name */
        } else {
            session_message(session, "Deleted mailbox: \"%s\"",
                            utf8_from_imaputf7(request->pool, mailbox));
            folderlist_delete(session->folderlist, mailbox);
            if (favourite_delete(fl, mailbox))
                options->save = T;
        }
    }

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