summaryrefslogtreecommitdiffstats
path: root/tasklst.c
blob: 84d674e1bb1dbe3247531f36d21a863d928cbc3b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/* See LICENSE file for copyright and license details. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "tasklst.h"

static int tasklst_tasks_status(TaskLst tasks, int status);

static int
tasklst_tasks_status(TaskLst tasks, int status)
{
	int i, total;
	
	for (i = 0, total = 0; i < TASK_LST_MAX_NUM; ++i) {
		if (tasks.status[i] == status)
			++total;
	}

	return total;
}

void
tasklst_init(TaskLst *tasks)
{
	int i;

	tasks->expiry = 0;

	for (i = 0; i < TASK_LST_MAX_NUM; ++i) {
		memset(&tasks->status[i], TASK_VOID, sizeof(int));
		memset(tasks->tdesc[i], 0, TASK_LST_DESC_MAX_SIZE);
	}
}

void
tasklst_set_expiration(TaskLst *tasks)
{
	tasks->expiry = time(NULL) + TASK_LST_EXPIRY;
}

int
tasklst_expired(TaskLst tasks)
{
	return ((time(NULL) - tasks.expiry) > TASK_LST_EXPIRY) ? 0 : -1;
}

int
tasklst_tasks_total(TaskLst tasks)
{
	return tasklst_tasks_todo(tasks) + tasklst_tasks_done(tasks);
}

int
tasklst_tasks_todo(TaskLst tasks)
{
	return tasklst_tasks_status(tasks, TASK_TODO);
}

int
tasklst_tasks_done(TaskLst tasks)
{
	return tasklst_tasks_status(tasks, TASK_DONE);
}
		
int
tasklst_read_from_file(TaskLst *tasks, FILE *fp)
{
	int i, stat_buf;
	char *ptr, *endptr;
	char linebuf[TASK_LST_DESC_MAX_SIZE];
	
	fgets(linebuf, sizeof(linebuf), fp);
	tasks->expiry = strtoul(linebuf, &endptr, 10);
	if (endptr[0] != '\n')
		return -1;

	for (i = 0; i < TASK_LST_MAX_NUM && feof(fp) == 0; ++i) {
		if (fgets(linebuf, sizeof(linebuf), fp) == NULL)
			break;

		ptr = strtok(linebuf, "\t");
		if (ptr == NULL)
			return -1;

		stat_buf = strtol(ptr, &endptr, 10);
		if (endptr[0] != '\0')
			return -1;

		if (stat_buf == TASK_VOID)
			break;
		else
			tasks->status[i] = stat_buf;

		ptr = strtok(NULL, "\n");
		if (ptr == NULL)
			return -1;

		strncpy(tasks->tdesc[i], ptr, TASK_LST_DESC_MAX_SIZE);
	}

	return 0;
}

void
tasklst_write_to_file(FILE *fp, TaskLst tasks)
{
	int i;

	fprintf(fp, "%zu\n", tasks.expiry);

	for (i = 0; i < TASK_LST_MAX_NUM; ++i) {
		if (tasks.status[i] == TASK_VOID)
			break;

		fprintf(fp, "%d\t%s\n", tasks.status[i], tasks.tdesc[i]);
	}
}