/* $Cambridge: hermes/src/prayer/cmd/cmd_dictionary.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"

static void generate_form(struct session *session, struct buffer *b)
{
    struct template_vals *tvals = session->template_vals;
    struct options *options = session->options;
    struct dictionary *dictionary = options->dictionary;
    struct list_item *li;
    unsigned long i, len, max, perline, count;

    /* Find maximum length of list item */
    count = 0;
    max = 1;
    for (li = dictionary->list->head; li; li = li->next) {
        if ((len = strlen(li->name)) > max)
            max = len;
        count++;
    }

    if ((max > 0) && (max < 38))
        perline = 80 / (max + 5);
    else
        perline = 1;

    if (count > 0) {
        for (i = 0, li = dictionary->list->head; li; li = li->next, i++) {
            template_vals_foreach_init(tvals, "@words", i);
            template_vals_foreach_string(tvals, "@words", i, "word", li->name);

            if ((i % perline) == (perline - 1))
                template_vals_foreach_ulong(tvals, "@words", i, "break", 1);
        }
    }

    session_seed_template(session, tvals);
    template_expand("dictionary", tvals, b);
}

void cmd_dictionary(struct session *session)
{
    struct request *request = session->request;
    struct buffer *b = request->write_buffer;
    struct assoc *h = NIL;
    struct options *options = session->options;
    struct dictionary *dictionary = options->dictionary;
    char *s, *line, *word;

    if (request->method != POST) {
        request_decode_form(request);
        h = request->form;
        if ((s = assoc_lookup(h, "remove")) && s[0]) {
            dictionary_remove(dictionary, s);
            options->save = T;
        }

        generate_form(session, b);
        response_html(request, 200);
        return;
    }

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

    if (assoc_lookup(h, "sub_cancel")) {
        session_redirect(session, request, "manage");
        return;
    }

    /* Add or remove words from dictionary */

    if (assoc_lookup(h, "sub_add")) {
        line = assoc_lookup(h, "add");
        while ((word = string_get_token(&line))) {
            if (word[0]) {
                dictionary_add(dictionary, word);
                options->save = T;
            }
        }
    } else if (assoc_lookup(h, "sub_remove")) {
        line = assoc_lookup(h, "remove");
        while ((word = string_get_token(&line))) {
            if (word[0]) {
                dictionary_remove(dictionary, word);
                options->save = T;
            }
        }
    }

    generate_form(session, b);
    response_html(request, 200);
}
