import 'dart:convert';

import 'package:fis_jsonrpc/encrpyt.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:vitalapp/architecture/storage/text_storage.dart';
import 'package:vitalapp/managers/interfaces/system_setting.dart';
import 'package:vitalapp/rpc.dart';
import 'package:vitalapp/store/store.dart';
import 'package:fis_common/logger/logger.dart';

class SystemSettingManager implements ISystemSettingManager {
  final _storage =
      TextStorage(fileName: "system_settings.cfg", directory: "settings");

  SyncSettingsDTO? _cache;

  @override
  Future<SyncSettingsDTO> getSettings([isRefresh = false]) async {
    if (_cache == null || isRefresh) {
      await _loadSettings();
      _cache ??= SyncSettingsDTO();
      _handleSettingsAbout(_cache!);
    }

    return _cache!;
  }

  Future<void> _loadSettings() async {
    _cache = await _loadSettingsFromStorage();

    // TODO: 判断是否在线，再请求rpc
    SyncSettingsDTO? remoteSettings = await _getSettingsFromRpc();
    if (remoteSettings == null) {
      return;
    }

    _cache = remoteSettings;
    final jsonText = jsonEncode(remoteSettings.toJson());
    await _storage.save(jsonText);
  }

  void _handleSettingsAbout(SyncSettingsDTO dto) {
    Store.app.enableEncryptSensitiveInfo = dto.encryptSensitiveInfo;
    Store.app.homePageUrl = dto.homePageUrl ?? '';
    rpc.requestEncryptConfig = JsonRpcEncryptConfig(
      enable: dto.enableRequestEncrypt,
      encryptMode: dto.requestEncryptMode ?? "",
      encryptKey: dto.requestEncryptKey ?? "",
    );
    rpc.responseEncryptConfig = JsonRpcEncryptConfig(
      enable: dto.enableResponseEncrypt,
      encryptMode: dto.responseEncryptMode ?? "",
      encryptKey: Store.user.token ?? "",
    );
  }

  Future<SyncSettingsDTO?> _getSettingsFromRpc() async {
    try {
      final request = SyncSettingRequest(token: Store.user.token);
      final result = await rpc.systemSetting.syncSettingAsync(request);
      return result;
    } catch (e) {
      logger.e("SystemSettingManager sync settings from rpc error.", e);
      return null;
    }
  }

  Future<SyncSettingsDTO?> _loadSettingsFromStorage() async {
    try {
      final jsonText = await _storage.read();
      if (jsonText == null) {
        return null;
      }
      final jsonMap = jsonDecode(jsonText);
      final dto = SyncSettingsDTO.fromJson(jsonMap);
      return dto;
    } catch (e) {
      logger.e("SystemSettingManager load settings from storage error.", e);
      return null;
    }
  }

  @override
  Future<List<String>> getEnableDeviceKeysAsync() async {
    try {
      final request = GetEnableDeviceKeysRequest(
          token: Store.user.token,
          organizationCode: Store.user.organizationCode);
      final result = await rpc.organization.getEnableDeviceKeysAsync(request);
      return result;
    } catch (e) {
      logger.e("SystemSettingManager getEnableDeviceKeysAsync error.", e);
      return [];
    }
  }
}
