1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
2//
3// SPDX-License-Identifier: AGPL-3.0-or-later
4
5package init
6
7import (
8 "errors"
9 "fmt"
10
11 "github.com/charmbracelet/huh"
12
13 "git.secluded.site/lune/internal/config"
14)
15
16func configureDefaults(cfg *config.Config) error {
17 hasAreas := len(cfg.Areas) > 0
18 hasNotebooks := len(cfg.Notebooks) > 0
19
20 if !hasAreas && !hasNotebooks {
21 return handleNoDefaultsAvailable(cfg)
22 }
23
24 if hasAreas {
25 if err := selectDefaultArea(cfg); err != nil {
26 return err
27 }
28 }
29
30 if hasNotebooks {
31 if err := selectDefaultNotebook(cfg); err != nil {
32 return err
33 }
34 }
35
36 return nil
37}
38
39func handleNoDefaultsAvailable(cfg *config.Config) error {
40 var action string
41
42 err := huh.NewSelect[string]().
43 Title("No areas or notebooks configured").
44 Description("You need at least one area or notebook to set defaults.").
45 Options(
46 huh.NewOption("Add an area now", "area"),
47 huh.NewOption("Add a notebook now", "notebook"),
48 huh.NewOption("Back", choiceBack),
49 ).
50 Value(&action).
51 Run()
52 if err != nil {
53 if errors.Is(err, huh.ErrUserAborted) {
54 return errQuit
55 }
56
57 return err
58 }
59
60 switch action {
61 case "area":
62 return addArea(cfg)
63 case "notebook":
64 return addNotebook(cfg)
65 }
66
67 return nil
68}
69
70func selectDefaultArea(cfg *config.Config) error {
71 areaOptions := []huh.Option[string]{
72 huh.NewOption("None", ""),
73 }
74 for _, area := range cfg.Areas {
75 areaOptions = append(areaOptions, huh.NewOption(
76 fmt.Sprintf("%s (%s)", area.Name, area.Key),
77 area.Key,
78 ))
79 }
80
81 defaultArea := cfg.Defaults.Area
82
83 err := huh.NewSelect[string]().
84 Title("Default area").
85 Description("Used when no area is specified in commands.").
86 Options(areaOptions...).
87 Value(&defaultArea).
88 Run()
89 if err != nil {
90 if errors.Is(err, huh.ErrUserAborted) {
91 return errQuit
92 }
93
94 return err
95 }
96
97 cfg.Defaults.Area = defaultArea
98
99 return nil
100}
101
102func selectDefaultNotebook(cfg *config.Config) error {
103 notebookOptions := []huh.Option[string]{
104 huh.NewOption("None", ""),
105 }
106 for _, notebook := range cfg.Notebooks {
107 notebookOptions = append(notebookOptions, huh.NewOption(
108 fmt.Sprintf("%s (%s)", notebook.Name, notebook.Key),
109 notebook.Key,
110 ))
111 }
112
113 defaultNotebook := cfg.Defaults.Notebook
114
115 err := huh.NewSelect[string]().
116 Title("Default notebook").
117 Description("Used when no notebook is specified in commands.").
118 Options(notebookOptions...).
119 Value(&defaultNotebook).
120 Run()
121 if err != nil {
122 if errors.Is(err, huh.ErrUserAborted) {
123 return errQuit
124 }
125
126 return err
127 }
128
129 cfg.Defaults.Notebook = defaultNotebook
130
131 return nil
132}