package ru.yandex.direct.api.v5.entity.dynamicfeedadtargets.converter;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.yandex.direct.api.v5.dynamicfeedadtargets.DynamicFeedAdTargetFieldEnum;
import com.yandex.direct.api.v5.dynamicfeedadtargets.GetRequest;
import com.yandex.direct.api.v5.general.AdTargetStateSelectionEnum;

import ru.yandex.direct.core.entity.dynamictextadtarget.container.DynamicTextAdTargetSelectionCriteria;
import ru.yandex.direct.core.entity.dynamictextadtarget.model.DynamicTextAdTargetState;
import ru.yandex.direct.utils.converter.Converters;

import static org.apache.commons.collections4.CollectionUtils.isEmpty;
import static ru.yandex.direct.api.v5.entity.dynamicfeedadtargets.converter.CommonConverter.API_TO_CORE_STATES;

public class GetRequestConverter {
    private static final Set<DynamicFeedAdTargetFieldEnum> DEFAULT_FIELD_NAMES =
            Set.of(DynamicFeedAdTargetFieldEnum.ID);

    private static final Set<DynamicTextAdTargetState> ALL_STATES = Set.of(
            DynamicTextAdTargetState.ON,
            DynamicTextAdTargetState.OFF,
            DynamicTextAdTargetState.SUSPENDED,
            DynamicTextAdTargetState.DELETED);

    public static Set<DynamicFeedAdTargetFieldEnum> getDynamicFeedAdTargetFieldEnums(GetRequest getRequest) {
        List<DynamicFeedAdTargetFieldEnum> fieldNames = getRequest.getFieldNames();
        if (isEmpty(fieldNames)) {
            return DEFAULT_FIELD_NAMES;
        }
        return new HashSet<>(fieldNames);
    }

    public static DynamicTextAdTargetSelectionCriteria getDynamicTextAdTargetSelectionCriteria(GetRequest getRequest) {
        var selectionCriteria = getRequest.getSelectionCriteria();
        List<Long> ids = selectionCriteria.getIds();

        return new DynamicTextAdTargetSelectionCriteria()
                .withConditionIds(new HashSet<>(ids))
                .withAdGroupIds(new HashSet<>(selectionCriteria.getAdGroupIds()))
                .withCampaignIds(new HashSet<>(selectionCriteria.getCampaignIds()))
                .withStates(convertStates(selectionCriteria.getStates(), ids.isEmpty()));
    }

    // дублирует логику dynamictextadtargets/converter/GetRequestConverter.java:convertStates
    public static Set<DynamicTextAdTargetState> convertStates(List<AdTargetStateSelectionEnum> states,
                                                              boolean idsIsEmpty) {
        Set<DynamicTextAdTargetState> resultStates =
                Converters.immutableSetConverter(API_TO_CORE_STATES).convert(states);

        if (!resultStates.isEmpty()) {
            return resultStates;
        }

        if (!idsIsEmpty) {
            return ALL_STATES;
        }

        return ALL_STATES.stream()
                .filter(state -> state != DynamicTextAdTargetState.DELETED)
                .collect(Collectors.toSet());
    }
}
