match_magic/lib/db/main_db.dart

104 lines
2.8 KiB
Dart

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<bool> 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<void> 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<void> 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<bool> getSoundEnabled() async {
final settings = await isar.settings.where().findFirst();
return settings?.isSoundEnabled ?? true;
}
Future<bool> getMusicEnabled() async {
final settings = await isar.settings.where().findFirst();
return settings?.isMusicEnabled ?? true;
}
Future<void> 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<int?> getHighScoreValue() async {
final highScore = await isar.highScores.where().findFirst();
return highScore?.highScoreValue;
}
}