from dataclasses import dataclass from models.Habit import Habit from models.User import User from db.SQLiteClient import (create_habitList, get_habitList, get_habits, get_users, add_user, remove_user, update_habitList, delete_habitList, habitList_get_next_slot, habitList_get_slots, habitList_update_slot) @dataclass class HabitList: id: int name: str description: str slot: int habits: list = None @staticmethod def create(user_id: int, name: str, description: str): slot = habitList_get_next_slot(user_id) id = create_habitList(user_id, name, description, slot) return HabitList(id, name, description, slot) @staticmethod def get(id: int): habitList = get_habitList(id) return HabitList(habitList[0], habitList[1], habitList[2], habitList[3]) if habitList else None # Updates: name, description def update(self): update_habitList(self.id, self.name, self.description) # Updates the slot and reorders the HabitLists accordingly def update_slot(self,user_id: int, new_slot: int): # Fetches a list with the following structure [(id, slot), (id, slot), ...] slots = habitList_get_slots(user_id) # Splits the list depending on whether the new slot is higher or lower than the current one if new_slot > self.slot: # Example self.slot=1 new_slot=4 slots = slots[self.slot:new_slot] # Expected list: [(id, 2), (id, 3), (id, 4)] for slot in slots: habitList_update_slot(slot[0], slot[1]-1) if new_slot < self.slot: # Example self.slot=4 new_slot=1 slots = slots[new_slot-1:self.slot-1] # Expected list: [(id, 1), (id, 2), (id, 3)] for slot in slots: habitList_update_slot(slot[0], slot[1]+1) # Update the slot of the current habitList habitList_update_slot(self.id, new_slot) # Deletes the HabitList | The id of the current user is necessary def delete(self, user_id): # Reorders the slots slots = habitList_get_slots(user_id)[self.slot+1:] for slot in slots: habitList_update_slot(slot[0], slot[1] - 1) if len(get_users(self.id)) > 1: self.remove_user(user_id) else: for habit in self.get_habits(): habit.delete() delete_habitList(self.id) # Returns the Habits connected with the HabitList def get_habits(self) -> list: raw_habits = get_habits(self.id) habits = [] for habit in raw_habits: habit = Habit(habit[0], habit[1], habit[2], habit[3], habit[4], habit[5], habit[6], habit[7], habit[8], habit[9]) habits.append(habit) return habits # Returns the Users connected with the HabitList def get_users(self) -> list: raw_users = get_users(self.id) users = [] for user in raw_users: user = User(user[0], user[1], user[2], user[3], user[4], user[5]) users.append(user) return users # Adds a User by email to the HabitList def add_user(self, user: User): if user: add_user(self.id, user.id) else: return None # Removes a User from the HabitList def remove_user(self, user_id): remove_user(self.id, user_id)