forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrptodo.py
More file actions
69 lines (58 loc) · 2.33 KB
/
Copy pathrptodo.py
File metadata and controls
69 lines (58 loc) · 2.33 KB
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
"""This module provides the RP To-Do model-controller."""
from pathlib import Path
from typing import Any, Dict, List, NamedTuple
from rptodo import DB_READ_ERROR, ID_ERROR
from rptodo.database import DatabaseHandler
class CurrentTodo(NamedTuple):
todo: Dict[str, Any]
error: int
class Todoer:
def __init__(self, db_path: Path) -> None:
self._db_handler = DatabaseHandler(db_path)
def add(self, description: List[str], priority: int = 2) -> CurrentTodo:
"""Add a new to-do to the database."""
description_text = " ".join(description)
if not description_text.endswith("."):
description_text += "."
todo = {
"Description": description_text,
"Priority": priority,
"Done": False,
}
read = self._db_handler.read_todos()
if read.error == DB_READ_ERROR:
return CurrentTodo(todo, read.error)
read.todo_list.append(todo)
write = self._db_handler.write_todos(read.todo_list)
return CurrentTodo(todo, write.error)
def get_todo_list(self) -> List[Dict[str, Any]]:
"""Return the current to-do list."""
read = self._db_handler.read_todos()
return read.todo_list
def set_done(self, todo_id: int) -> CurrentTodo:
"""Set a to-do as done."""
read = self._db_handler.read_todos()
if read.error:
return CurrentTodo({}, read.error)
try:
todo = read.todo_list[todo_id - 1]
except IndexError:
return CurrentTodo({}, ID_ERROR)
todo["Done"] = True
write = self._db_handler.write_todos(read.todo_list)
return CurrentTodo(todo, write.error)
def remove(self, todo_id: int) -> CurrentTodo:
"""Remove a to-do from the database using its id or index."""
read = self._db_handler.read_todos()
if read.error:
return CurrentTodo({}, read.error)
try:
todo = read.todo_list.pop(todo_id - 1)
except IndexError:
return CurrentTodo({}, ID_ERROR)
write = self._db_handler.write_todos(read.todo_list)
return CurrentTodo(todo, write.error)
def remove_all(self) -> CurrentTodo:
"""Remove all to-dos from the database."""
write = self._db_handler.write_todos([])
return CurrentTodo({}, write.error)