import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/repository/description_repository.dart';
import 'package:aitrainer_app/service/logging.dart';
import 'package:firebase_remote_config/firebase_remote_config.dart';

class SplitTestRepository with Logging {
  final RemoteConfig? _remoteConfig = Cache().remoteConfig;
  final DescriptionRepository descriptionRepository = DescriptionRepository();

  String getSplitTestValue(String remoteConfigKey) {
    String testValue = "";

    if (_remoteConfig != null) {
      _remoteConfig!.fetchAndActivate();
      Map configs = _remoteConfig!.getAll();
      RemoteConfigValue? value = configs[remoteConfigKey];
      if (value != null) {
        log("A/B Test RemoteConfig $remoteConfigKey value: ${value.asString()}");
        final String remoteConfigValue = value.asString();
        testValue = this.getSplitTestValueByRemoteConfig(remoteConfigKey, remoteConfigValue);
      } else {
        log("RemoteConfig value $remoteConfigKey is null!!");
      }
    } else {
      log(" !! remoteConfig isnull");
    }

    return testValue;
  }

  String getSource(String remoteConfigKey) {
    String source = "";

    return source;
  }

  String getSplitTestValueByRemoteConfig(String key, String value) {
    String testValue = "";
    if (Cache().getSplitTests().isEmpty) {
      log("Splittests empty");
      return testValue;
    }

    Cache().getSplitTests().forEach((element) {
      if (element.remoteConfigKey == key && element.remoteConfigValue == value && element.active) {
        testValue = element.testValue;
        log("A/B Test testValue: $testValue");

        if (element.source != null && element.source!.isNotEmpty) {
          final List<String> sourceElements = element.source!.split(".");
          if (sourceElements.length > 1) {
            final String modelName = sourceElements[0];
            if (modelName == "description") {
              testValue = descriptionRepository.getDescriptionByName(element.testValue);
            }
          }
        }
      }
    });

    return testValue;
  }
}