import 'package:injectable/injectable.dart';
import 'package:keyboard/data/api/response/character_custom_config_response.dart';

import '../../base/app_base_request.dart';
import '../../utils/async_util.dart';
import '../../utils/atmob_log.dart';
import '../../utils/http_handler.dart';
import '../api/atmob_api.dart';
import '../api/request/config_request.dart';
import '../api/response/config_response.dart';

import 'package:get/get.dart';

import '../bean/custom_config_info.dart';

@lazySingleton
class ConfigRepository {
  final tag = "ConfigRepository";

  final AtmobApi atmobApi;

  final Rxn<CustomConfigInfo> _characterCustomConfig = Rxn<CustomConfigInfo>();

  CustomConfigInfo? get characterCustomConfig => _characterCustomConfig.value;

  ConfigRepository(this.atmobApi) {
    AtmobLog.d(tag, '$tag....init');
    refreshConfig();
    refreshCharacterCustomConfig();
  }

  // 更新配置的值
  void refreshConfig() {
    AsyncUtil.retry(
      () => requestConfigsData(),
      Duration(seconds: 3),
      maxRetry: 100,
    ).then((configsResponse) {
      final list = configsResponse.list;
      if (list == null || list.isEmpty) {
        return;
      }
    });
  }

  Future<void> refreshCharacterCustomConfig() async {
    try {
      final value = await getCharacterCustomConfig();
      _characterCustomConfig.value = value.customConfig;
    } catch (e) {
      AtmobLog.e(tag, "获取定制人设配置失败: $e");
    }
  }

  /// 获取配置信息
  Future<ConfigResponse> requestConfigsData() {
    return atmobApi
        .confs(ConfigRequest(confCodes: ['intimacy', 'default_avatar']))
        .then(HttpHandler.handle(true));
  }

  /// 获取定制人设配置
  Future<CharacterCustomConfigResponse> getCharacterCustomConfig() {
    return atmobApi
        .getCharacterCustomConfig(AppBaseRequest())
        .then(HttpHandler.handle(true));
  }
}
