Added an "add" command.
[ctodo.git] / list.c
blob3fd1da64b97de4b7f3e0e5b2d700e949f4a696dd
1 #include <list.h>
2 #include <sqlite3.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <time.h>
7 void list_help() {
8 printf(" Usage: list\n");
9 printf(" Lists all the tasks and their children.\n");
12 int print_children(sqlite3 *db, int parent, int depth) {
13 sqlite3_stmt *statement;
14 char *query;
16 if (parent == -1) {
17 query = sqlite3_mprintf("SELECT * FROM todo WHERE (parent IS NULL) ORDER BY key ASC;");
18 } else {
19 query = sqlite3_mprintf("SELECT * FROM todo WHERE (parent = %d) ORDER BY key ASC;", parent);
22 int retVal = sqlite3_prepare_v2(db, query, -1, &statement, NULL);
23 if (retVal != SQLITE_OK) {
24 printf("An error occurred while trying to fetch the todo's from the database: %s\n", sqlite3_errmsg(db));
25 sqlite3_finalize(statement);
26 return 1;
29 while ((retVal = sqlite3_step(statement)) == SQLITE_ROW) {
30 time_t startDate, dueDate;
31 const unsigned char *hasDueDate = sqlite3_column_text(statement, 3);
32 startDate = (time_t) sqlite3_column_int(statement, 2);
33 printf("%-*sTodo #%d: %s\n", depth*2, "", sqlite3_column_int(statement, 0), sqlite3_column_text(statement, 1));
34 printf("%-*sCreated on: %s", depth*2, "", ctime(&startDate));
35 if (hasDueDate) {
36 dueDate = (time_t) sqlite3_column_int(statement, 3);
37 printf("%-*sDue on: %s", depth*2, "", ctime(&dueDate));
38 } else {
39 printf("%-*sNo due date.\n", depth*2, "");
41 printf("\n");
42 print_children(db, sqlite3_column_int(statement, 0), depth+1);
45 sqlite3_free(query);
46 sqlite3_finalize(statement);
48 return 0;
51 int list(sqlite3 *db, MArray tokens) {
52 if (tokens->len == 2 && !strcmp(myarray_get(tokens, char *, 1), "help")) {
53 list_help();
54 return 0;
55 } else if (tokens->len > 1) {
56 printf("Invalid amount of arguments.\n");
57 list_help();
58 return 0;
61 return print_children(db, -1, 0);