Files
vpn/lib/models/storage_model.dart
2026-04-05 11:54:37 +03:00

81 lines
2.0 KiB
Dart

import 'package:hive_flutter/hive_flutter.dart';
import 'package:vpn/models/config.dart';
final class StorageModel {
StorageModel();
static const String _boxName = 'storage';
static const String _configsKey = 'configs';
static const String _selectedKey = 'selected';
Future<bool> init() async {
await Hive.initFlutter();
if (!Hive.isAdapterRegistered(0)) {
Hive.registerAdapter(ConfigAdapter());
}
_box = await Hive.openBox<dynamic>(_boxName);
final List<dynamic> rawConfigs =
_box.get(_configsKey, defaultValue: <dynamic>[]) as List<dynamic>;
_configs = rawConfigs.whereType<Config>().toList();
_selected = _box.get(_selectedKey, defaultValue: -1) as int;
if (_selected < 0 || _selected >= _configs.length) {
_selected = _configs.isEmpty ? -1 : 0;
_box.put(_selectedKey, _selected);
}
isInit = true;
return true;
}
void addConfig(String name, String config) {
if (!isInit) return;
final Config newConfig = Config();
newConfig.name = name;
newConfig.config = config;
_configs.add(newConfig);
_box.put(_configsKey, _configs);
if (_selected == -1) {
_selected = 0;
_box.put(_selectedKey, _selected);
}
}
void removeConfig(int index) {
if (!isInit) return;
if (index < 0 || index >= _configs.length) return;
_configs.removeAt(index);
_box.put(_configsKey, _configs);
if (_configs.isEmpty) {
_selected = -1;
} else if (_selected == index) {
_selected = index >= _configs.length ? _configs.length - 1 : index;
} else if (_selected > index) {
_selected -= 1;
}
_box.put(_selectedKey, _selected);
}
set selected(int index) {
if (!isInit) return;
if (index < -1 || index >= _configs.length) return;
_selected = index;
_box.put(_selectedKey, _selected);
}
List<Config> get configs => _configs;
int get selected => _selected;
late Box<dynamic> _box;
List<Config> _configs = [];
int _selected = -1;
bool isInit = false;
}