HabitTracker/models/Habit.py
2024-01-26 10:01:02 +01:00

72 lines
2.2 KiB
Python

from dataclasses import dataclass
from datetime import datetime
from models.HabitTrackings import HabitTrackings
from db.SQLiteClient import update_slot, create_habit, get_habit, delete_habit, get_next_slot, \
get_habitTrackings_by_habit_id, get_slots, update_habit
# Unit wird als Integers wie folgt gemessen:
# 0: Tag
# 1: Woche (Default)
# 2: Monat
# 3: Jahr
@dataclass
class Habit:
id: int
user_id: int
name: str
note: str
times: int
unit: int
slot: int
@staticmethod
def create(user_id: int, name: str, times: int, note: str | None = None, unit: int | None = 1):
slot = get_next_slot(user_id)
id = create_habit(user_id, name, times, unit, slot, note)
return Habit(id, user_id, name, note, times, unit, slot)
@staticmethod
def get(id: int):
habit = get_habit(id)
return Habit(habit[0], habit[1], habit[2], habit[3], habit[4], habit[5], habit[6]) if habit else None
def update(self, name: str=None, note: str=None, times: int=None, unit: int=None):
update_habit(self.id, name, note, times, unit)
if name is not None:
self.name = name
if note is not None:
self.note = note
if times is not None:
self.times = times
if unit is not None:
self.unit = unit
# So sollte die Slots Liste aussehen damit es funktioniert
#[(id, 1), (id, 2), (id, 3), (id, 4), (id, 5)]
def update_slot(self, new_slot: int):
slots = get_slots(self.user_id)
if new_slot > self.slot:
slots = slots[self.slot:new_slot]
for slot in slots:
update_slot(slot[0], slot[1]-1)
if new_slot < self.slot:
slots = slots[new_slot-1:self.slot-1]
for slot in slots:
update_slot(slot[0], slot[1]+1)
self.slot = new_slot
def delete(self):
delete_habit(self.id)
def get_habitTrackings(self) -> list[HabitTrackings]:
trackings = []
for rawTracking in get_habitTrackings_by_habit_id(self.id):
trackings.append(HabitTrackings(rawTracking[0], rawTracking[1], rawTracking[2], datetime.strptime(rawTracking[3], "%Y-%m-%dT%H:%M:%S.%f")))
return trackings