Dr-Blank.Vaani/lib/settings/api_settings_provider.dart

62 lines
1.8 KiB
Dart
Raw Normal View History

2024-05-08 05:03:49 -04:00
// this provider is used to provide the Api settings to the app
2024-06-28 06:01:56 -04:00
import 'package:logging/logging.dart';
2024-05-08 05:03:49 -04:00
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:whispering_pages/db/available_boxes.dart';
2024-05-09 00:41:19 -04:00
import 'package:whispering_pages/settings/models/api_settings.dart' as model;
2024-05-08 05:03:49 -04:00
part 'api_settings_provider.g.dart';
final _box = AvailableHiveBoxes.apiSettingsBox;
2024-06-28 06:01:56 -04:00
final _logger = Logger('ApiSettingsProvider');
2024-05-14 06:13:16 -04:00
@Riverpod(keepAlive: true)
2024-05-08 05:03:49 -04:00
class ApiSettings extends _$ApiSettings {
@override
model.ApiSettings build() {
state = readFromBoxOrCreate();
ref.listenSelf((_, __) {
writeToBox();
});
return state;
}
model.ApiSettings readFromBoxOrCreate() {
// see if the settings are already in the box
if (_box.isNotEmpty) {
var foundSettings = _box.getAt(0);
// foundSettings.activeServer ??= foundSettings.activeUser?.server;
// foundSettings =foundSettings.copyWith(activeServer: foundSettings.activeUser?.server);
if (foundSettings.activeServer == null) {
foundSettings = foundSettings.copyWith(
activeServer: foundSettings.activeUser?.server,
);
}
2024-06-28 06:01:56 -04:00
_logger.fine('found api settings in box: $foundSettings');
2024-05-08 05:03:49 -04:00
return foundSettings;
} else {
// create a new settings object
const settings = model.ApiSettings();
2024-06-28 06:01:56 -04:00
_logger.fine('created new api settings: $settings');
2024-05-08 05:03:49 -04:00
return settings;
}
}
// write the settings to the box
void writeToBox() {
_box.clear();
_box.add(state);
2024-06-28 06:01:56 -04:00
_logger.fine('wrote api settings to box: $state');
2024-05-08 05:03:49 -04:00
}
2024-05-09 00:41:19 -04:00
void updateState(model.ApiSettings newSettings, {bool force = false}) {
// check if the settings are different
if (state == newSettings && !force) {
return;
}
2024-05-08 05:03:49 -04:00
state = newSettings;
}
}