addMeal method

Future<int?> addMeal({
  1. required Meal meal,
  2. required int userID,
})

Adds a new meal to the database.

  • meal: The meal object to be added.

Returns the ID of the newly created meal.

Implementation

Future<int?> addMeal({required Meal meal, required int userID}) async {
  await _databaseWrapper.ensureDBIsInitialized();

  // Step 1: Check if the day already exists, if not create a new one
  List<Map<String, dynamic>> dayRecords = await _databaseWrapper.database.query(
    'days',
    where: 'year = ? AND month = ? AND day = ?',
    whereArgs: [meal.year, meal.month, meal.day],
  );
  int dayID;
  if (dayRecords.isEmpty) {
    dayID = await _databaseWrapper.database.insert(
      'days',
      {'year': meal.year, 'month': meal.month, 'day': meal.day},
    );
  } else {
    dayID = dayRecords.first['ID'];
  }

  // Step 2: Get the meal type ID
  List<Map<String, dynamic>> mealTypeRecords = await _databaseWrapper.database.query(
    'meal_types',
    where: 'LOWER(name) = ?',
    whereArgs: [meal.mealType.toLowerCase()],
  );
  if (mealTypeRecords.isEmpty) {
    throw Exception('Invalid meal type: ${meal.mealType}');
  }
  int mealTypeID = mealTypeRecords.first['ID'];

  // Step 3: Insert the new meal
  int mealID = await _databaseWrapper.database.insert(
    'meals',
    {'fat_level': meal.fatLevel, 'sugar_level': meal.sugarLevel},
    conflictAlgorithm: ConflictAlgorithm.replace,
  );

  // Step 4: Link the meal to the day and meal type in day_meals
  List<Map<String, dynamic>> dayMealRecords = await _databaseWrapper.database.query(
    'day_meals',
    where: 'fk_user_id = ? AND fk_day_id = ? AND fk_meal_type_id = ?',
    whereArgs: [userID, dayID, mealTypeID],
  );
  if (dayMealRecords.isNotEmpty) {
    return null; // Meal already exists for this day and meal type
  }

  await _databaseWrapper.database.insert(
    'day_meals',
    {
      'fk_user_id': userID,
      'fk_day_id': dayID,
      'fk_meal_type_id': mealTypeID,
      'fk_meal_id': mealID,
    },
  );

  return mealID;
}