import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:location/base/app_base_request.dart';
import 'package:location/data/api/atmob_api.dart';
import 'package:location/data/api/request/configs_request.dart';
import 'package:location/data/api/request/upload_client_id_request.dart';
import 'package:location/data/bean/config_bean.dart';
import 'package:location/data/repositories/friends_repository.dart';
import 'package:location/data/repositories/phone_event_repository.dart';
import 'package:location/di/get_it.dart';
import 'package:location/utils/async_util.dart';
import 'package:location/utils/http_handler.dart';

import '../api/response/configs_response.dart';
import '../api/response/user_avatar_response.dart';

@lazySingleton
class ConfigRepository {
  final String tag = 'ConfigRepository';

  static const String keyVirtualFriend = 'virtual_friend';
  static const String keyClientScheduled = 'client_scheduled';

  bool? _isShowVirtualFriend;

  final Rxn<bool> isOpenFreeMember = Rxn<bool>();

  List<String>? userAvatarList;

  final AtmobApi atmobApi;

  final FriendsRepository friendsRepository;

  ConfigRepository(this.atmobApi, this.friendsRepository) {
    refreshConfig();
  }

  static ConfigRepository getInstance() {
    return getIt.get<ConfigRepository>();
  }

  void refreshConfig() {
    AsyncUtil.retry(() => requestConfigsData(), Duration(seconds: 3),
            maxRetry: 100)
        .then((configsResponse) {
      final list = configsResponse.list;
      if (list == null || list.isEmpty) {
        return;
      }
      for (var item in list) {
        final confCode = item.confCode;
        switch (confCode) {
          case keyVirtualFriend:
            _dealWithVirtualFriendSetting(item);
            break;
          case keyClientScheduled:
            _dealWithClientScheduledSetting(item);
            break;
        }
      }
    });
  }

  void _dealWithClientScheduledSetting(ConfigBean item) {
    final cfg = item.value;
    if (cfg == null || cfg.isEmpty == true) {
      return;
    }
    if (cfg.containsKey("phoneEventMinutes")) {
      final phoneEventMinutes = cfg["phoneEventMinutes"];
      if (phoneEventMinutes is double && phoneEventMinutes > 0) {
        PhoneEventRepository.getInstance()
            .setTaskIntervalTime(Duration(minutes: phoneEventMinutes.toInt()));
      }
    }
  }

  Future<ConfigsResponse> requestConfigsData() {
    return atmobApi
        .getConfigs(ConfigsRequest([keyVirtualFriend, keyClientScheduled]))
        .then(HttpHandler.handle(true));
  }

  void _dealWithVirtualFriendSetting(ConfigBean item) {
    final cfg = item.value;
    if (cfg == null || cfg.isEmpty == true) {
      return;
    }
    // virtualFriendEnabled 是否开启虚拟好友
    if (cfg.containsKey("virtualFriendEnabled")) {
      _isShowVirtualFriend = cfg["virtualFriendEnabled"];
      if (_isShowVirtualFriend == true) {
        friendsRepository.refreshVirtualFriend();
      }
    }
    //freeMemberEnabled 是否开启免费会员体验
    if (cfg.containsKey("freeMemberEnabled")) {
      isOpenFreeMember.value = cfg["freeMemberEnabled"];
    }
  }

  Future<void> uploadClientId(String clientId) {
    return atmobApi
        .uploadClientId(UploadClientIdRequest(clientId))
        .then(HttpHandler.handle(true));
  }

  Future<List<String>> requestUserAvatarList() {
    if (userAvatarList != null && userAvatarList!.isNotEmpty) {
      return Future.value(userAvatarList);
    }
    return atmobApi
        .userAvatarList(AppBaseRequest())
        .then(HttpHandler.handle(false))
        .then((response) {
      final list = response.list;
      userAvatarList = list;
      if (list == null) {
        throw Exception("User avatar list is null");
      }
      return list;
    });
  }
}
