insertEntry method

Future<void> insertEntry(
  1. DiaryEntry entry,
  2. String userId,
  3. String optionalLocation
)

Inserts a DiaryEntry into the local database for a specific user.

If optionalLocation is provided, it overrides the reverse geolocation lookup. Otherwise, a location is derived using _geolocatorService. Automatically removes the oldest entries if the user exceeds maxEntries.

Implementation

Future<void> insertEntry(
  DiaryEntry entry,
  String userId,
  String optionalLocation,
) async {
  final db = await database;

  final position = Position(
    latitude: entry.latitude,
    longitude: entry.longitude,
    timestamp: entry.date,
    accuracy: 0,
    altitude: 0,
    heading: 0,
    speed: 0,
    altitudeAccuracy: 0,
    headingAccuracy: 0,
    speedAccuracy: 0,
  );

  String location;
  if (optionalLocation.isNotEmpty) {
    location = optionalLocation;
  } else {
    try {
      location = await _geolocatorService.getCityAndCountryFromPosition(
        position,
      );
    } catch (e) {
      location = 'Sconosciuta';
    }
  }

  final entryMap =
      entry.toJson()
        ..['userId'] = userId
        ..['photoUrls'] = entry.photoUrls.join(',')
        ..['location'] = location;

  await db.insert(
    'diary_entries',
    entryMap,
    conflictAlgorithm: ConflictAlgorithm.replace,
  );

  final countResult = await db.rawQuery(
    'SELECT COUNT(*) as count FROM diary_entries WHERE userId = ?',
    [userId],
  );
  final count = Sqflite.firstIntValue(countResult) ?? 0;

  if (count > maxEntries) {
    final excess = count - maxEntries;

    await db.delete(
      'diary_entries',
      where: '''
        id IN (
          SELECT id FROM diary_entries
          WHERE userId = ?
          ORDER BY date ASC
          LIMIT ?
        )
      ''',
      whereArgs: [userId, excess],
    );
  }
}