/* $Cambridge: hermes/src/prayer/cmd/cmd_abook_sort.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_sort(struct session *session)
{
    struct abook   *abook   = session->options->abook;
    struct request *request = session->request;
    char *type, *text = "";
    BOOL reverse;

    if (request->argc < 2) {
        session_redirect(session, request, "abook_list");
        return;
    }
    
    type    = request->argv[1];
    reverse = abook->sort_reverse;

    if (!strcmp(type, "order")) {
        if (abook->sort_mode == ABOOK_SORT_ORDER) {
            reverse = (reverse) ? NIL : T;
            abook_set_sort(abook, ABOOK_SORT_ORDER, reverse);
        } else
            abook_set_sort(abook, ABOOK_SORT_ORDER, reverse=NIL);
        text = "order";
    } else if (!strcmp(type, "alias")) {
        if (abook->sort_mode == ABOOK_SORT_ALIAS) {
            reverse = (reverse) ? NIL : T;
            abook_set_sort(abook, ABOOK_SORT_ALIAS, reverse);
        } else
            abook_set_sort(abook, ABOOK_SORT_ALIAS, reverse=NIL);
        text = "alias";
    } else if (!strcmp(type, "name")) {
        if (abook->sort_mode == ABOOK_SORT_NAME) {
            reverse = (reverse) ? NIL : T;
            abook_set_sort(abook, ABOOK_SORT_NAME, reverse);
        } else
            abook_set_sort(abook, ABOOK_SORT_NAME, NIL);
        text = "name";
    } else if (!strcmp(type, "comment")) {
        if (abook->sort_mode == ABOOK_SORT_COMMENT) {
            reverse = (reverse) ? NIL : T;
            abook_set_sort(abook, ABOOK_SORT_COMMENT, reverse);
        } else
            abook_set_sort(abook, ABOOK_SORT_COMMENT, reverse=NIL);
        text = "comment";
    } else if (!strcmp(type, "email")) {
        if (abook->sort_mode == ABOOK_SORT_EMAIL) {
            reverse = (reverse) ? NIL : T;
            abook_set_sort(abook, ABOOK_SORT_EMAIL, reverse);
        } else
            abook_set_sort(abook, ABOOK_SORT_EMAIL, reverse=NIL);
        text = "address(es)";
    }

    if (reverse)
        session_message(session, "Sorting on reverse %s", text);
    else
        session_message(session, "Sorting on %s", text);

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