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

/// 本地硬件设置缓存服务
class HardwareSettingService extends GetxService {
  String _cache = "";

  /// 获取设置的缓存
  void restoreLocalCache() {
    try {
      var map = json.decode(_cache);
      HardwareSetting.ins.setDataFromJson(map);
    } catch (e) {
      logger.e('HardwareSettingService restoreLocalCache ex:', e);
    }
  }

  static const _SETTING_FILENAME = "hardware_setting.conf";
  TextStorage _entryStorage = TextStorage.createInstance(_SETTING_FILENAME);

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

  ///保存配置
  Future<bool> save() async {
    var jsonStr = json.encode(HardwareSetting.ins.toJson());
    return _entryStorage.save(jsonStr);
  }

  // 同步至Shell
  // TODO: 后期扩展为允许双向同步
  Future<void> syncToShell() async {
    await rpc.platform
        .reloadSettings(json.encode(HardwareSetting.ins.toJson()));
  }

  /// 同步来自另一端的配置
  void syncFromJson(String jsonStr) {
    try {
      var map = json.decode(jsonStr);
      HardwareSetting.ins.setDataFromJson(map);
      save();
    } catch (e) {
      logger.e('HardwareSettingService syncFromShell ex:', e);
    }
  }
}
