Advertisement
harmonyV

Database controlle

Jul 26th, 2024
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 5.65 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'package:habit_tracker/models/app_settings.dart';
  3. import 'package:habit_tracker/services/extensions/day.dart';
  4. import 'package:habit_tracker/models/habit.dart';
  5. import 'package:habit_tracker/services/lists_enums_maps.dart';
  6. import 'package:isar/isar.dart';
  7. import 'package:path_provider/path_provider.dart';
  8.  
  9. class HabitDatabase extends ChangeNotifier {
  10.   static late Isar isar;
  11.  
  12.   // I N I T I A L I Z E - D A T A B A S E
  13.   HabitDatabase() {
  14.     readHabitsFromDatabase();
  15.   }
  16.  
  17.   static Future<void> initialize() async {
  18.     final directory = await getApplicationCacheDirectory();
  19.     isar = await Isar.open(
  20.       [HabitSchema, AppSettingsSchema],
  21.       directory: directory.path,
  22.     );
  23.   }
  24.  
  25.   // save first date of app startup (for heatmap)
  26.   static Future<void> saveFirstLaunchDate() async {
  27.     final existingSettings = await isar.appSettings.where().findFirst();
  28.     if (existingSettings == null) {
  29.       final settings = AppSettings()..firstLaunchDate = DateTime.now();
  30.       await isar.writeTxn(() => isar.appSettings.put(settings));
  31.     }
  32.   }
  33.  
  34.   // get first date of app startup (for heatmap)
  35.   Future<DateTime?> getFirstLaunchDate() async {
  36.     final settings = await isar.appSettings.where().findFirst();
  37.     return settings?.firstLaunchDate;
  38.   }
  39.  
  40.   final _listOfHabits = <Habit>[];
  41.   List<Habit> get listOfHabits => _listOfHabits;
  42.  
  43.   final _listOfHabitsInProgress = <Habit>[];
  44.   List<Habit> get listOfHabitsInProgress => _listOfHabitsInProgress;
  45.  
  46.   final _listOfCompletedHabits = <Habit>[];
  47.   List<Habit> get listOfCompletedHabits => _listOfCompletedHabits;
  48.  
  49.   var _selection = Selection.inProgress;
  50.   Selection get selection => _selection;
  51.  
  52.   void setSelection(Selection newSelection) {
  53.     switch (newSelection) {
  54.       case Selection.inProgress:
  55.         _selection = newSelection;
  56.         break;
  57.       case Selection.completed:
  58.         _selection = newSelection;
  59.         break;
  60.       case Selection.overdue:
  61.         _selection = newSelection;
  62.         break;
  63.       default:
  64.     }
  65.  
  66.     notifyListeners();
  67.   }
  68.  
  69.   // C R E A T E - add a new habit
  70.  
  71.   Future<void> addHabit(
  72.     String habitName,
  73.     String? details,
  74.     List<int> itemDataIntKeys,
  75.     HabitCategory habitCategory,
  76.   ) async {
  77.     debugPrint(
  78.         "USED FOR CREATING HABIT; DATA_KEY_STRING_LIST; $itemDataIntKeys");
  79.     debugPrint("USED FOR CREATING HABIT; HABIT_CATEGORY; $habitCategory");
  80.  
  81.     final newHabit = Habit(name: habitName, category: habitCategory);
  82.     newHabit.details = details;
  83.     newHabit.itemDataIntKeys.addAll(itemDataIntKeys);
  84.  
  85.     // save to database
  86.     await isar.writeTxn(() => isar.habits.put(newHabit));
  87.  
  88.     readHabitsFromDatabase();
  89.   }
  90.  
  91.   // R E A D - read saved habits from database
  92.   Future<void> readHabitsFromDatabase() async {
  93.     final fetchedHabits = await isar.habits.where().findAll();
  94.  
  95.     _listOfHabits.clear();
  96.     _listOfHabits.addAll(fetchedHabits);
  97.  
  98.     _listOfHabitsInProgress.clear();
  99.     _listOfCompletedHabits.clear();
  100.  
  101.     // check each habit in _listOfHabits for todays completion status
  102.     for (final habitToCheck in _listOfHabits) {
  103.       debugPrint("${habitToCheck.completedDays.contains(Day.now())}");
  104.       // if habit is NOT completed today => add it to _listOfHabitsInProgress
  105.       if (!habitToCheck.completedDays.contains(Day.now())) {
  106.         _listOfHabitsInProgress.add(habitToCheck);
  107.       }
  108.       // if habit IS completed today => add it to the _listOfCompletedHabits
  109.       else if (habitToCheck.completedDays.contains(Day.now())) {
  110.         _listOfCompletedHabits.add(habitToCheck);
  111.       }
  112.     }
  113.     setSelection(_selection);
  114.  
  115.     notifyListeners();
  116.   }
  117.  
  118.   // U P D A T E - check habit on and off
  119.  
  120.   Future<void> updateHabitCompletion(int id, bool isCompleted) async {
  121.     // find the specific habit
  122.     final habit = await isar.habits.get(id);
  123.  
  124.     // update completion status
  125.     if (habit != null) {
  126.       await isar.writeTxn(() async {
  127.         // if habit is completed => add the current date to the completedDays list
  128.         if (isCompleted && !habit.completedDays.contains(Day.now())) {
  129.           // addd the current date if it's not already in the list
  130.           habit.completedDays.checkDay(Day.now());
  131.         }
  132.         // if habit is NOT completed => remove current date from the completedDays list
  133.         else {
  134.           // remove the current date if the habit is marked as NOT completed
  135.           habit.completedDays.uncheckDay(Day.now());
  136.           //habit.completedDays.removeWhere((date) => date == Day.now());
  137.         }
  138.  
  139.         // save the updated habits back to the database
  140.         await isar.habits.put(habit);
  141.       });
  142.     }
  143.  
  144.     await readHabitsFromDatabase();
  145.   }
  146.  
  147.   // U P D A T E - edit habit name
  148.  
  149.   Future<void> editHabit(
  150.     int id,
  151.     String newName,
  152.     String? newDetails,
  153.     List<int> newitemDataIntKeys,
  154.     HabitCategory newHabitCategory,
  155.   ) async {
  156.     // find the specific habit
  157.     final habit = await isar.habits.get(id);
  158.  
  159.     // update habit name, itemKeyStringsList, category
  160.     if (habit != null) {
  161.       await isar.writeTxn(() async {
  162.         habit.name = newName;
  163.         habit.details = newDetails;
  164.         habit.itemDataIntKeys = [];
  165.         habit.itemDataIntKeys.addAll(newitemDataIntKeys);
  166.         habit.category = newHabitCategory;
  167.  
  168.         // save updated habit back to database
  169.         await isar.habits.put(habit);
  170.       });
  171.     }
  172.  
  173.     readHabitsFromDatabase();
  174.   }
  175.  
  176.   // D E L E T E
  177.  
  178.   Future<void> deleteHabit(int id) async {
  179.     await isar.writeTxn(() async {
  180.       await isar.habits.delete(id);
  181.     });
  182.  
  183.     readHabitsFromDatabase();
  184.   }
  185. }
  186.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement