/* $Cambridge: hermes/src/prayer/cmd/cmd_abook_lookup_add.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_abook_lookup_add(struct session *session)
{
    struct draft *draft = session->draft;
    struct request *request = session->request;
    struct assoc  *h = NIL;
    char *field, *name, *email, *full;

    if (!draft) {
        session_message(session,
                        "Error: abook_lookup_add called without active draft");
        session_redirect(session, request, "abook_list");
        return;
    }

    request_decode_form(request);
    h = request->form;

    field = assoc_lookup(h, "field");
    name  = assoc_lookup(h, "name");
    email = assoc_lookup(h, "email");

    if (!(field && field[0] && name && name[0] && email && email[0])) {
        session_message(session,
                        "Error: abook_lookup_add called with missing args");
        session_redirect(session, request, "abook_list");
        return;
    }

    string_canon_decode(name);
    string_canon_decode(email);

    full = abook_text_to_string(request->pool, name, email);

    if (!strcmp(field, "to")) {
        draft_add_to(draft, full);
        session_message(session, "Added %s to To", email);
    } else if (!strcmp(field, "cc")) {
        draft_add_cc(draft, full);
        session_message(session, "Added %s to Cc", email);
    } else if (!strcmp(field, "bcc")) {
        draft_add_bcc(draft, full);
        session_message(session, "Added %s to Bcc", email);
    } else
        session_message(session,
                        "Error: abook_lookup_add called with invalid field");

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