package ru.yandex.qe.dispenser.ws.quota.request.owning_cost.formula;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.google.common.collect.ImmutableMap;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import ru.yandex.qe.dispenser.api.util.EnumUtils;
import ru.yandex.qe.dispenser.api.v1.DiUnit;
import ru.yandex.qe.dispenser.domain.QuotaChangeRequest;
import ru.yandex.qe.dispenser.ws.bot.Provider;
import ru.yandex.qe.dispenser.ws.quota.request.owning_cost.ChangeOwningCostContext;
import ru.yandex.qe.dispenser.ws.quota.request.owning_cost.pricing.QuotaChangeOwningCostTariffManager;

@Component
public class RtmrMirrorOwningCostFormula implements ProviderOwningCostFormula {

    private static final Logger LOG = LoggerFactory.getLogger(RtmrMirrorOwningCostFormula.class);

    private static final Provider PROVIDER = Provider.RTMR_MIRROR;
    private static final BigDecimal KPS_PRICE = new BigDecimal("1.15", MATH_CONTEXT);

    public RtmrMirrorOwningCostFormula() {
    }

    @Override
    public @NotNull String getProviderKey() {
        return PROVIDER.getServiceKey();
    }

    public @NotNull Map<QuotaChangeRequest.ChangeKey, BigDecimal> calculateOwningCostFromContext(
            @NotNull Collection<ChangeOwningCostContext> changes) {
        Map<QuotaChangeRequest.ChangeKey, BigDecimal> result = new HashMap<>();
        Map<CampaignKey, List<ChangeOwningCostContext>> changesByCampaign = ProviderOwningCostFormula
                .groupByCampaign(changes, result);
        changesByCampaign.forEach((campaignKey, campaignChanges) -> {
            if (QuotaChangeOwningCostTariffManager.CAMPAIGN_KEYS_2022.contains(campaignKey.getKey())) {
                // No RTMR mirror resources in 2022 campaign
                campaignChanges.forEach(change -> result.put(change.getChange().getKey(), DEFAULT_OWNING_COST));
            } else {
                Map<QuotaChangeRequest.ChangeKey, BigDecimal> campaignCosts = campaignChanges.stream()
                        .map(ChangeOwningCostContext::getChange)
                        .collect(Collectors.toMap(QuotaChangeRequest.ChangeAmount::getKey, this::toOwningCost));
                result.putAll(campaignCosts);
            }
        });
        return result;
    }

    private BigDecimal toOwningCost(QuotaChangeRequest.Change change) {
        BigDecimal result = DEFAULT_OWNING_COST;
        String publicKey = change.getResource().getPublicKey();
        Optional<Resource> resourcesO = Resource.byKey(publicKey);
        if (resourcesO.isPresent()) {
            switch (resourcesO.get()) {
                case KPS:
                    result = calculateForKps(change);
                    break;
                case DATA:
                    break;
            }
        }
        return result;
    }

    private BigDecimal calculateForKps(QuotaChangeRequest.Change change) {
        return convert(change, DiUnit.COUNT, LOG).multiply(KPS_PRICE, MATH_CONTEXT);
    }

    private enum Resource implements EnumUtils.StringKey {
        DATA("data"),
        KPS("kps"),
        ;

        private static Map<String, Resource> resourceByKey;
        private final String key;

        Resource(String key) {
            this.key = key;
        }

        public String getKey() {
            return key;
        }

        public static Optional<Resource> byKey(String key) {
            if (Resource.resourceByKey == null) {
                Resource.resourceByKey = ImmutableMap.copyOf(EnumUtils.prepareKeysMap(Resource.values()));
            }
            return Optional.ofNullable(Resource.resourceByKey.get(key));
        }
    }

}
