import 'dart:convert';
import 'package:fis_common/logger/logger.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/architecture/storage/text_storage.dart';
import 'package:get/get.dart';

class LocalSettingService extends GetxService with _LocalSettingMixin {
  static const _SETTING_FILENAME = "local_setting.conf";
  TextStorage _settingStorage = TextStorage.createInstance(_SETTING_FILENAME);

  ///初始化
  Future<void> init() async {
    // 创建实例
    final list = await _settingStorage.fetch();
    if (list == null) {
      _cache = "";
    } else {
      _cache = list;
      getLocalCache();
    }
  }

  ///保存配置
  Future<bool> save() async {
    var jsonStr = LocalSetting.ins.toJson();
    return _settingStorage.save(jsonStr);
  }
}

mixin _LocalSettingMixin {
  String _cache = "";

  /// 获取设置的缓存
  LocalSetting? getLocalCache() {
    try {
      var map = json.decode(_cache);
      return LocalSetting.ins.fromJson(map);
    } catch (e) {
      logger.e('LocalSettingService getLocalCache ex:', e);
    }
    logger.e('getLocalCache is null');
    return null;
  }
}
