import 'dart:convert';

import 'package:flyinsono/architecture/config/model.dart';
import 'package:flyinsono/architecture/storage/text_storage.dart';
import 'package:get/get.dart';
import 'package:fis_common/logger/logger.dart';

/// 配置服务
class ConfigService extends GetxService {
  ConfigService._() {
    _persistenceStorage = TextStorage.createInstance(_PERSISTENCE_FILENAME);
  }

  /// 全局单例
  static ConfigService get ins => Get.find();

  ///持久化配置文件名
  static const _PERSISTENCE_FILENAME = "config.conf";

  late TextStorage _persistenceStorage;
  late ConfigModel _cache;

  /// 配置数据
  ConfigModel get data => _cache;

  /// 实例初始化
  static Future<ConfigService> init() async {
    if (Get.isRegistered<ConfigService>()) return ins;

    final instance = ConfigService._();
    await instance._loadPersistenceData();
    return instance;
  }

  ///重新加载
  static Future<ConfigService> reload() async {
    if (Get.isRegistered<ConfigService>()) {
      Get.delete<ConfigService>(force: true);
    }
    final instance = ConfigService._();
    await instance._loadPersistenceData();
    return instance;
  }

  /// 保存配置
  Future<bool> save() async {
    try {
      final jsonMap = _cache.toJson();
      final jsonText = jsonEncode(jsonMap);
      final saved = await _persistenceStorage.save(jsonText);
      return saved;
    } catch (e) {
      logger.e("ConfigService save data error.", e);
      return false;
    }
  }

  Future<void> _loadPersistenceData() async {
    try {
      var text = await _persistenceStorage.fetch();
      _setDataFromJson(text);
    } catch (e) {
      logger.e("ConfigService load persistence data error.", e);
    }
  }

  void _setDataFromJson(String? jsonText) {
    final isObjJson = jsonText != null &&
        jsonText.length > 1 &&
        jsonText.startsWith("{") &&
        jsonText.endsWith("}");
    var jsonMap = jsonDecode(isObjJson ? jsonText : "{}");
    _cache = ConfigModel.fromJson(jsonMap);
  }
}
