#include <glib.h>
#include <glib/gi18n.h>
#include <glib-object.h>
#include <libecal/e-cal.h>

#include "koto-task-store.h"
#include "ical-util.h"

typedef enum {
  OP_HELP,
  OP_LIST,
} Operation;

static gboolean
print_task (GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data)
{
  gboolean done = FALSE;
  int weight = 0;
  char *summary = NULL;

  gtk_tree_model_get (model, iter,
                      COLUMN_DONE, &done,
                      COLUMN_WEIGHT, &weight,
                      COLUMN_SUMMARY, &summary,
                      -1);

  if (done) {
    g_free (summary);
    return TRUE;
  }

  if (weight < PRIORITY_MEDIUM)
    g_print ("+ ");
  else if (weight > PRIORITY_MEDIUM)
    g_print ("- ");
  else
    g_print ("  ");
  
  g_print ("%s\n", summary);

  g_free (summary);
  return FALSE;
}

static void
view_done (ECalView *view, ECalendarStatus status, GMainLoop *loop)
{
  if (status != E_CALENDAR_STATUS_OK) {
    g_print ("Cannot read contacts: %d", status);
  }  
  g_main_loop_quit (loop);
}

static Operation
get_op (int argc, char **argv)
{
  /* No arguments, show tasks */
  if (argc == 1)
    return OP_LIST;

  if (argc > 1) {
    if (g_ascii_strcasecmp (argv[1], "list") == 0)
      return OP_LIST;
  }
  
  return OP_HELP;
}

int
main (int argc, char **argv)
{
  GError *error = NULL;
  GMainLoop *loop;
  Operation op;
  ECal *cal;
  ECalView *view;
  GtkTreeModel *store;

#ifdef ENABLE_NLS
  bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
  textdomain (GETTEXT_PACKAGE);
#endif

  g_type_init ();
  loop = g_main_loop_new (NULL, TRUE);

  op = get_op (argc, argv);
  switch (op) {
  case OP_HELP:
    g_print ("$ tasks-cli list\n");
    return 0;
  default:
    break;
  }
  
  cal = e_cal_new_system_tasks ();
  if (!cal)
    g_error ("Cannot get system tasks");
  
  if (!e_cal_open (cal, FALSE, &error))
    g_error ("Cannot open calendar: %s", error->message);
  
  switch (op) {
  case OP_LIST:
    if (!e_cal_get_query (cal, "#t", &view, &error))
      g_error ("Cannot get calendar view: %s", error->message);
    g_signal_connect (view, "view-done", G_CALLBACK (view_done), loop);
    store = koto_task_store_new (view);
    e_cal_view_start (view);
    g_main_loop_run (loop);
    gtk_tree_model_foreach (store, print_task, NULL);
    g_object_unref (view);
    break;

    /* We've already handled these operations, but include them here to say we
       know about them */
  case OP_HELP:
    break;
  }

  g_object_unref (cal);
  g_main_loop_unref (loop);
  return 0;
}
