File size: 10,029 Bytes
5be081e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Menu/UX Layer for Interactive Todo Application

Owner: Menu/UX Agent
Purpose: Display menus, collect user input, render task lists

Constitutional Constraints:
- ALLOWED: Menu display (print()), User input (input()), Input validation, Service layer calls
- FORBIDDEN: SQL queries, Database connections, Business logic validation, Schema changes
"""

from typing import Optional
from models import Task
import services


def display_menu() -> None:
    """
    Display main menu options to user.

    Menu Options:
        1. Create New Task
        2. View All Tasks
        3. Update Task
        4. Toggle Task Completion
        5. Delete Task
        6. Exit

    Constitutional Compliance:
        βœ… Display only (no input collection)
        βœ… NO SQL queries
        βœ… NO business logic
    """
    print("\n" + "=" * 50)
    print("         INTERACTIVE TODO APPLICATION")
    print("=" * 50)
    print("1. Create New Task")
    print("2. View All Tasks")
    print("3. Update Task")
    print("4. Toggle Task Completion")
    print("5. Delete Task")
    print("6. Exit")
    print("=" * 50)


def get_menu_choice() -> str:
    """
    Get and validate menu selection from user.

    Returns:
        User's menu choice as string ('1' through '6')

    Implementation Notes:
        - Prompts user for input
        - Validates choice is in valid range (1-6)
        - Loops until valid input received
        - Returns validated choice as string

    Constitutional Compliance:
        βœ… Input validation (format only)
        βœ… NO business logic validation
        βœ… NO database operations
    """
    while True:
        choice = input("\nEnter your choice (1-6): ").strip()

        if choice in ['1', '2', '3', '4', '5', '6']:
            return choice
        else:
            print("Invalid choice. Please enter a number between 1 and 6.")


def handle_create_task(conn) -> None:
    """
    Collect task details and create task via service layer.

    Args:
        conn: Active database connection to pass to service layer

    Implementation Notes:
        - Prompts for title (required)
        - Prompts for description (optional)
        - Validates input is non-empty for title
        - Calls services.create_task() with connection
        - Displays success or error message from service layer

    Constitutional Compliance:
        βœ… Input collection only
        βœ… Calls service layer for business logic
        βœ… NO SQL queries
        βœ… NO business validation (delegates to service layer)
    """
    print("\n--- Create New Task ---")

    # Collect title (required)
    title = input("Enter task title: ").strip()

    if not title:
        print("Error: Title cannot be empty.")
        return

    # Collect description (optional)
    description = input("Enter task description (optional, press Enter to skip): ").strip()

    # If description is empty string, pass None
    if not description:
        description = None

    # Call service layer to create task
    result = services.create_task(conn, title, description)

    # Display result from service layer
    if result['success']:
        print(f"\nβœ“ {result['message']}")
    else:
        print(f"\nβœ— {result['message']}")


def format_task_display(task: Task) -> str:
    """
    Format task for terminal display.

    Args:
        task: Task object to format

    Returns:
        Formatted string with status icon, ID, title, and description

    Format:
        [βœ“] #123: Task title - Description preview...
        [β—‹] #456: Another task

    Implementation Notes:
        - Uses βœ“ for completed tasks, β—‹ for incomplete tasks
        - Shows task ID, title, and truncated description
        - Leverages Task.__str__() method for consistent formatting

    Constitutional Compliance:
        βœ… Display formatting only
        βœ… NO business logic
        βœ… NO database operations
    """
    return str(task)


def handle_list_tasks(conn) -> None:
    """
    Display all tasks in readable format via service layer.

    Args:
        conn: Active database connection to pass to service layer

    Implementation Notes:
        - Calls services.list_tasks() with connection
        - Formats and displays each task using format_task_display()
        - Shows count of tasks
        - Displays message if no tasks exist

    Constitutional Compliance:
        βœ… Display only
        βœ… Calls service layer for data retrieval
        βœ… NO SQL queries
        βœ… NO business logic
    """
    print("\n--- All Tasks ---")

    # Call service layer to retrieve tasks
    result = services.list_tasks(conn)

    if not result['success']:
        print(f"\nβœ— {result['message']}")
        return

    tasks = result['tasks']

    if not tasks:
        print("\nNo tasks found. Create your first task!")
        return

    print(f"\nTotal tasks: {len(tasks)}\n")

    # Display each task
    for task in tasks:
        print(format_task_display(task))


def handle_update_task(conn) -> None:
    """
    Collect task ID and new details, update task via service layer.

    Args:
        conn: Active database connection to pass to service layer

    Implementation Notes:
        - Prompts for task ID
        - Validates ID is a positive integer
        - Prompts for new title (optional)
        - Prompts for new description (optional)
        - Ensures at least one field is provided
        - Calls services.update_task() with connection
        - Displays success or error message from service layer

    Constitutional Compliance:
        βœ… Input collection and format validation
        βœ… Calls service layer for business logic
        βœ… NO SQL queries
        βœ… NO business validation (delegates to service layer)
    """
    print("\n--- Update Task ---")

    # Collect task ID
    task_id_input = input("Enter task ID to update: ").strip()

    try:
        task_id = int(task_id_input)
        if task_id <= 0:
            print("Error: Task ID must be a positive integer.")
            return
    except ValueError:
        print("Error: Invalid task ID. Please enter a number.")
        return

    # Collect new title (optional)
    print("\nLeave field empty to keep current value:")
    new_title = input("Enter new title (or press Enter to skip): ").strip()

    # If empty, set to None to indicate no change
    if not new_title:
        new_title = None

    # Collect new description (optional)
    new_description = input("Enter new description (or press Enter to skip): ").strip()

    # If empty, set to None to indicate no change
    if not new_description:
        new_description = None

    # Validate at least one field is provided
    if new_title is None and new_description is None:
        print("Error: Must provide at least one field to update (title or description).")
        return

    # Call service layer to update task
    result = services.update_task(conn, task_id, new_title, new_description)

    # Display result from service layer
    if result['success']:
        print(f"\nβœ“ {result['message']}")
    else:
        print(f"\nβœ— {result['message']}")


def handle_toggle_task(conn) -> None:
    """
    Collect task ID and toggle completion via service layer.

    Args:
        conn: Active database connection to pass to service layer

    Implementation Notes:
        - Prompts for task ID
        - Validates ID is a positive integer
        - Calls services.toggle_task_completion() with connection
        - Displays success or error message from service layer

    Constitutional Compliance:
        βœ… Input collection and format validation
        βœ… Calls service layer for business logic
        βœ… NO SQL queries
        βœ… NO business logic
    """
    print("\n--- Toggle Task Completion ---")

    # Collect task ID
    task_id_input = input("Enter task ID to toggle: ").strip()

    try:
        task_id = int(task_id_input)
        if task_id <= 0:
            print("Error: Task ID must be a positive integer.")
            return
    except ValueError:
        print("Error: Invalid task ID. Please enter a number.")
        return

    # Call service layer to toggle task completion
    result = services.toggle_task_completion(conn, task_id)

    # Display result from service layer
    if result['success']:
        print(f"\nβœ“ {result['message']}")
    else:
        print(f"\nβœ— {result['message']}")


def handle_delete_task(conn) -> None:
    """
    Collect task ID and delete task via service layer.

    Args:
        conn: Active database connection to pass to service layer

    Implementation Notes:
        - Prompts for task ID
        - Validates ID is a positive integer
        - Prompts for confirmation (destructive action)
        - Calls services.delete_task() with connection
        - Displays success or error message from service layer

    Constitutional Compliance:
        βœ… Input collection and format validation
        βœ… Confirmation prompt for destructive action
        βœ… Calls service layer for business logic
        βœ… NO SQL queries
        βœ… NO business logic
    """
    print("\n--- Delete Task ---")

    # Collect task ID
    task_id_input = input("Enter task ID to delete: ").strip()

    try:
        task_id = int(task_id_input)
        if task_id <= 0:
            print("Error: Task ID must be a positive integer.")
            return
    except ValueError:
        print("Error: Invalid task ID. Please enter a number.")
        return

    # Confirmation prompt for destructive action
    confirmation = input(f"Are you sure you want to delete task #{task_id}? (yes/no): ").strip().lower()

    if confirmation not in ['yes', 'y']:
        print("Deletion cancelled.")
        return

    # Call service layer to delete task
    result = services.delete_task(conn, task_id)

    # Display result from service layer
    if result['success']:
        print(f"\nβœ“ {result['message']}")
    else:
        print(f"\nβœ— {result['message']}")