import 'package:electronic_assistant/base/app_base_request.dart';
import 'package:electronic_assistant/data/api/atmob_api.dart';
import 'package:electronic_assistant/utils/async_util.dart';
import 'package:electronic_assistant/utils/http_handler.dart';

import '../../utils/app_info_util.dart';
import '../api/request/config_request.dart';
import '../api/response/config_response.dart';
import '../api/response/example_info_response.dart';
import '../bean/config_bean.dart';
import '../bean/version_update_bean.dart';

class ConfigRepository {
  ConfigRepository._();

  ExampleInfoResponse? _exampleInfo;

  Future<ExampleInfoResponse> getExampleInfo() async {
    if (_exampleInfo != null) {
      return _exampleInfo!;
    }
    return await AsyncUtil.retry(
        () => _requestExampleInfo(), const Duration(seconds: 1),
        maxRetry: 3);
  }

  Future<ExampleInfoResponse> _requestExampleInfo() {
    return atmobApi
        .exampleInfo(AppBaseRequest())
        .then(HttpHandler.handle(true))
        .then((response) {
      _exampleInfo = response;
      return response;
    });
  }

  Future<ConfigResponse> configs(List<String> confCodes) {
    return atmobApi
        .configs(ConfigRequest(confCodes))
        .then(HttpHandler.handle(true));
  }

  Future<VersionUpdateBean?> getAppVersion() async {
    ConfigResponse configResponse = await configs(['app_update']);
    if (configResponse.list.isEmpty) {
      return null;
    }
    ConfigBean configBean = configResponse.list.first;
    if (configBean.value is! Map<String, dynamic>) {
      return null;
    }
    VersionUpdateBean bean = VersionUpdateBean.fromJson(configBean.value);
    String? localVersionName = appInfoUtil.appVersionName;
    if (bean.version.isEmpty || localVersionName == null) {
      return null;
    }
    if (needsUpdate(bean.version, localVersionName)) {
      return bean;
    }
    return null;
  }

  bool needsUpdate(String serverVersion, String localVersion) {
    List<int> serverParts =
        serverVersion.replaceFirst('v', '').split('.').map(int.parse).toList();
    List<int> localParts = localVersion.split('.').map(int.parse).toList();

    for (int i = 0; i < serverParts.length; i++) {
      if (serverParts[i] > localParts[i]) {
        return true;
      } else if (serverParts[i] < localParts[i]) {
        return false;
      }
    }
    return false;
  }
}

final configRepository = ConfigRepository._();
