summaryrefslogtreecommitdiff
path: root/internal/handlers/handlers.go
blob: ed100fc1c2975cfe51f60198748058212cf2c039 (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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
package handlers

import (
	"context"
	"encoding/json"
	"html/template"
	"log"
	"net/http"
	"sync"
	"time"

	"task-dashboard/internal/api"
	"task-dashboard/internal/config"
	"task-dashboard/internal/models"
	"task-dashboard/internal/store"
)

// Handler holds dependencies for HTTP handlers
type Handler struct {
	store           *store.Store
	todoistClient   api.TodoistAPI
	trelloClient    api.TrelloAPI
	obsidianClient  api.ObsidianAPI
	planToEatClient api.PlanToEatAPI
	config          *config.Config
	templates       *template.Template
}

// New creates a new Handler instance
func New(store *store.Store, todoist api.TodoistAPI, trello api.TrelloAPI, obsidian api.ObsidianAPI, planToEat api.PlanToEatAPI, cfg *config.Config) *Handler {
	// Parse templates including partials
	tmpl, err := template.ParseGlob("web/templates/*.html")
	if err != nil {
		log.Printf("Warning: failed to parse templates: %v", err)
	}

	// Also parse partials
	tmpl, err = tmpl.ParseGlob("web/templates/partials/*.html")
	if err != nil {
		log.Printf("Warning: failed to parse partial templates: %v", err)
	}

	return &Handler{
		store:           store,
		todoistClient:   todoist,
		trelloClient:    trello,
		obsidianClient:  obsidian,
		planToEatClient: planToEat,
		config:          cfg,
		templates:       tmpl,
	}
}

// HandleDashboard renders the main dashboard view
func (h *Handler) HandleDashboard(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Extract tab query parameter for state persistence
	tab := r.URL.Query().Get("tab")
	if tab == "" {
		tab = "tasks"
	}

	// Aggregate data from all sources
	dashboardData, err := h.aggregateData(ctx, false)
	if err != nil {
		http.Error(w, "Failed to load dashboard data", http.StatusInternalServerError)
		log.Printf("Error aggregating data: %v", err)
		return
	}

	// Render template
	if h.templates == nil {
		http.Error(w, "Templates not loaded", http.StatusInternalServerError)
		return
	}

	// Wrap dashboard data with active tab for template
	data := struct {
		*models.DashboardData
		ActiveTab string
	}{
		DashboardData: dashboardData,
		ActiveTab:     tab,
	}

	if err := h.templates.ExecuteTemplate(w, "index.html", data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering template: %v", err)
	}
}

// HandleRefresh forces a refresh of all data
func (h *Handler) HandleRefresh(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	// Force refresh by passing true
	data, err := h.aggregateData(ctx, true)
	if err != nil {
		http.Error(w, "Failed to refresh data", http.StatusInternalServerError)
		log.Printf("Error refreshing data: %v", err)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(data)
}

// HandleGetTasks returns tasks as JSON
func (h *Handler) HandleGetTasks(w http.ResponseWriter, r *http.Request) {
	tasks, err := h.store.GetTasks()
	if err != nil {
		http.Error(w, "Failed to get tasks", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(tasks)
}

// HandleGetNotes returns notes as JSON
func (h *Handler) HandleGetNotes(w http.ResponseWriter, r *http.Request) {
	notes, err := h.store.GetNotes(20)
	if err != nil {
		http.Error(w, "Failed to get notes", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(notes)
}

// HandleGetMeals returns meals as JSON
func (h *Handler) HandleGetMeals(w http.ResponseWriter, r *http.Request) {
	startDate := time.Now()
	endDate := startDate.AddDate(0, 0, 7)

	meals, err := h.store.GetMeals(startDate, endDate)
	if err != nil {
		http.Error(w, "Failed to get meals", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(meals)
}

// HandleGetBoards returns Trello boards with cards as JSON
func (h *Handler) HandleGetBoards(w http.ResponseWriter, r *http.Request) {
	boards, err := h.store.GetBoards()
	if err != nil {
		http.Error(w, "Failed to get boards", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(boards)
}

// HandleTasksTab renders the tasks tab content (Trello + Todoist + PlanToEat)
func (h *Handler) HandleTasksTab(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	data, err := h.aggregateData(ctx, false)
	if err != nil {
		http.Error(w, "Failed to load tasks", http.StatusInternalServerError)
		log.Printf("Error loading tasks tab: %v", err)
		return
	}

	if err := h.templates.ExecuteTemplate(w, "tasks-tab", data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering tasks tab: %v", err)
	}
}

// HandleNotesTab renders the notes tab content (Obsidian)
func (h *Handler) HandleNotesTab(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	data, err := h.aggregateData(ctx, false)
	if err != nil {
		http.Error(w, "Failed to load notes", http.StatusInternalServerError)
		log.Printf("Error loading notes tab: %v", err)
		return
	}

	if err := h.templates.ExecuteTemplate(w, "notes-tab", data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering notes tab: %v", err)
	}
}

// HandleRefreshTab refreshes and re-renders the specified tab
func (h *Handler) HandleRefreshTab(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	tab := r.URL.Query().Get("tab") // "tasks" or "notes"

	// Force refresh
	data, err := h.aggregateData(ctx, true)
	if err != nil {
		http.Error(w, "Failed to refresh", http.StatusInternalServerError)
		log.Printf("Error refreshing tab: %v", err)
		return
	}

	// Determine template to render
	templateName := "tasks-tab"
	if tab == "notes" {
		templateName = "notes-tab"
	}

	if err := h.templates.ExecuteTemplate(w, templateName, data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering refreshed tab: %v", err)
	}
}

// aggregateData fetches and caches data from all sources
func (h *Handler) aggregateData(ctx context.Context, forceRefresh bool) (*models.DashboardData, error) {
	data := &models.DashboardData{
		LastUpdated: time.Now(),
		Errors:      make([]string, 0),
	}

	var wg sync.WaitGroup
	var mu sync.Mutex

	// Fetch Trello boards (PRIORITY - most important)
	wg.Add(1)
	go func() {
		defer wg.Done()
		boards, err := h.fetchBoards(ctx, forceRefresh)
		mu.Lock()
		defer mu.Unlock()
		if err != nil {
			data.Errors = append(data.Errors, "Trello: "+err.Error())
		} else {
			data.Boards = boards
		}
	}()

	// Fetch Todoist tasks
	wg.Add(1)
	go func() {
		defer wg.Done()
		tasks, err := h.fetchTasks(ctx, forceRefresh)
		mu.Lock()
		defer mu.Unlock()
		if err != nil {
			data.Errors = append(data.Errors, "Todoist: "+err.Error())
		} else {
			data.Tasks = tasks
		}
	}()

	// Fetch Obsidian notes (if configured)
	if h.obsidianClient != nil {
		wg.Add(1)
		go func() {
			defer wg.Done()
			notes, err := h.fetchNotes(ctx, forceRefresh)
			mu.Lock()
			defer mu.Unlock()
			if err != nil {
				data.Errors = append(data.Errors, "Obsidian: "+err.Error())
			} else {
				data.Notes = notes
			}
		}()
	}

	// Fetch PlanToEat meals (if configured)
	if h.planToEatClient != nil {
		wg.Add(1)
		go func() {
			defer wg.Done()
			meals, err := h.fetchMeals(ctx, forceRefresh)
			mu.Lock()
			defer mu.Unlock()
			if err != nil {
				data.Errors = append(data.Errors, "PlanToEat: "+err.Error())
			} else {
				data.Meals = meals
			}
		}()
	}

	wg.Wait()

	return data, nil
}

// fetchTasks fetches tasks from cache or API
func (h *Handler) fetchTasks(ctx context.Context, forceRefresh bool) ([]models.Task, error) {
	cacheKey := "todoist_tasks"

	// Check cache validity
	if !forceRefresh {
		valid, err := h.store.IsCacheValid(cacheKey)
		if err == nil && valid {
			return h.store.GetTasks()
		}
	}

	// Fetch from API
	tasks, err := h.todoistClient.GetTasks(ctx)
	if err != nil {
		// Try to return cached data even if stale
		cachedTasks, cacheErr := h.store.GetTasks()
		if cacheErr == nil && len(cachedTasks) > 0 {
			return cachedTasks, nil
		}
		return nil, err
	}

	// Save to cache
	if err := h.store.SaveTasks(tasks); err != nil {
		log.Printf("Failed to save tasks to cache: %v", err)
	}

	// Update cache metadata
	if err := h.store.UpdateCacheMetadata(cacheKey, h.config.CacheTTLMinutes); err != nil {
		log.Printf("Failed to update cache metadata: %v", err)
	}

	return tasks, nil
}

// fetchNotes fetches notes from cache or filesystem
func (h *Handler) fetchNotes(ctx context.Context, forceRefresh bool) ([]models.Note, error) {
	cacheKey := "obsidian_notes"

	// Check cache validity
	if !forceRefresh {
		valid, err := h.store.IsCacheValid(cacheKey)
		if err == nil && valid {
			return h.store.GetNotes(20)
		}
	}

	// Fetch from filesystem
	notes, err := h.obsidianClient.GetNotes(ctx, 20)
	if err != nil {
		// Try to return cached data even if stale
		cachedNotes, cacheErr := h.store.GetNotes(20)
		if cacheErr == nil && len(cachedNotes) > 0 {
			return cachedNotes, nil
		}
		return nil, err
	}

	// Save to cache
	if err := h.store.SaveNotes(notes); err != nil {
		log.Printf("Failed to save notes to cache: %v", err)
	}

	// Update cache metadata
	if err := h.store.UpdateCacheMetadata(cacheKey, h.config.CacheTTLMinutes); err != nil {
		log.Printf("Failed to update cache metadata: %v", err)
	}

	return notes, nil
}

// fetchMeals fetches meals from cache or API
func (h *Handler) fetchMeals(ctx context.Context, forceRefresh bool) ([]models.Meal, error) {
	cacheKey := "plantoeat_meals"

	// Check cache validity
	if !forceRefresh {
		valid, err := h.store.IsCacheValid(cacheKey)
		if err == nil && valid {
			startDate := time.Now()
			endDate := startDate.AddDate(0, 0, 7)
			return h.store.GetMeals(startDate, endDate)
		}
	}

	// Fetch from API
	meals, err := h.planToEatClient.GetUpcomingMeals(ctx, 7)
	if err != nil {
		// Try to return cached data even if stale
		startDate := time.Now()
		endDate := startDate.AddDate(0, 0, 7)
		cachedMeals, cacheErr := h.store.GetMeals(startDate, endDate)
		if cacheErr == nil && len(cachedMeals) > 0 {
			return cachedMeals, nil
		}
		return nil, err
	}

	// Save to cache
	if err := h.store.SaveMeals(meals); err != nil {
		log.Printf("Failed to save meals to cache: %v", err)
	}

	// Update cache metadata
	if err := h.store.UpdateCacheMetadata(cacheKey, h.config.CacheTTLMinutes); err != nil {
		log.Printf("Failed to update cache metadata: %v", err)
	}

	return meals, nil
}

// fetchBoards fetches Trello boards from cache or API
func (h *Handler) fetchBoards(ctx context.Context, forceRefresh bool) ([]models.Board, error) {
	cacheKey := "trello_boards"

	// Check cache validity
	if !forceRefresh {
		valid, err := h.store.IsCacheValid(cacheKey)
		if err == nil && valid {
			return h.store.GetBoards()
		}
	}

	// Fetch from API
	boards, err := h.trelloClient.GetBoardsWithCards(ctx)
	if err != nil {
		// Try to return cached data even if stale
		cachedBoards, cacheErr := h.store.GetBoards()
		if cacheErr == nil && len(cachedBoards) > 0 {
			return cachedBoards, nil
		}
		return nil, err
	}

	// Save to cache
	if err := h.store.SaveBoards(boards); err != nil {
		log.Printf("Failed to save boards to cache: %v", err)
	}

	// Update cache metadata
	if err := h.store.UpdateCacheMetadata(cacheKey, h.config.CacheTTLMinutes); err != nil {
		log.Printf("Failed to update cache metadata: %v", err)
	}

	return boards, nil
}