import 'package:isar/isar.dart'; import 'package:match_magic/models/isar/high_score.dart'; import 'package:match_magic/models/isar/settings.dart'; import 'package:path_provider/path_provider.dart'; class MainDB { MainDB._(); static MainDB? _instance; static MainDB get instance => _instance ??= MainDB._(); Isar? _isar; Isar get isar => _isar!; Future initMainDB({Isar? mock}) async { final dir = await getApplicationDocumentsDirectory(); if (mock != null) { _isar = mock; return true; } if (_isar != null && isar.isOpen) return false; _isar = await Isar.open( [SettingsSchema, HighScoreSchema], directory: dir.path, inspector: false, ); return true; } Future saveSoundEnabled(bool isEnabled) async { print('saveSoundEnabled $isEnabled'); final settings = await isar.settings.where().findFirst(); await isar.writeTxn(() async { if (settings != null) { settings.isSoundEnabled = isEnabled; await isar.settings.put(settings); } else { final newSettings = Settings( isSoundEnabled: isEnabled, isMusicEnabled: true, ); await isar.settings.put(newSettings); } }); } Future saveMusicEnabled(bool isEnabled) async { final settings = await isar.settings.where().findFirst(); await isar.writeTxn(() async { if (settings != null) { settings.isMusicEnabled = isEnabled; await isar.settings.put(settings); } else { final newSettings = Settings( isSoundEnabled: true, isMusicEnabled: isEnabled, ); await isar.settings.put(newSettings); } }); } Future getSoundEnabled() async { final settings = await isar.settings.where().findFirst(); return settings?.isSoundEnabled ?? true; } Future getMusicEnabled() async { final settings = await isar.settings.where().findFirst(); return settings?.isMusicEnabled ?? true; } Future addHighScore(int score, Function()? callback) async { final highScore = HighScore( highScoreValue: score, ); await isar.writeTxn(() async { final existingHighScore = await isar.highScores.where().findFirst(); if (existingHighScore != null) { if (score > existingHighScore.highScoreValue) { existingHighScore.highScoreValue = score; await isar.highScores.put(existingHighScore); } else { await isar.highScores.put(existingHighScore); } } else { await isar.highScores.put(highScore); } }); if (callback != null) { callback(); } } Future getHighScoreValue() async { final highScore = await isar.highScores.where().findFirst(); return highScore?.highScoreValue; } }