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

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

import com.google.common.collect.ImmutableSet;
import com.yandex.direct.api.v5.retargetinglists.GetRequest;
import com.yandex.direct.api.v5.retargetinglists.RetargetingListSelectionCriteria;
import com.yandex.direct.api.v5.retargetinglists.RetargetingListTypeEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import ru.yandex.direct.core.entity.retargeting.container.RetargetingSelectionCriteria;
import ru.yandex.direct.dbschema.ppc.enums.RetargetingConditionsRetargetingConditionsType;

import static ru.yandex.direct.dbschema.ppc.enums.RetargetingConditionsRetargetingConditionsType.interests;
import static ru.yandex.direct.dbschema.ppc.enums.RetargetingConditionsRetargetingConditionsType.metrika_goals;

@Component
@Service("retargetingGetRequestConverter")
public class GetRequestConverter implements Converter<GetRequest, RetargetingSelectionCriteria> {

    @Override
    public RetargetingSelectionCriteria convert(GetRequest getRequest) {
        RetargetingListSelectionCriteria selectionCriteria = getRequest.getSelectionCriteria();
        return new RetargetingSelectionCriteria()
                .withIds(selectionCriteria != null && !selectionCriteria.getIds().isEmpty()
                        ? new HashSet<>(selectionCriteria.getIds()) : null)
                .withTypes(selectionCriteria != null && !selectionCriteria.getTypes().isEmpty()
                        ? convertTypes(selectionCriteria.getTypes())
                        : ImmutableSet.of(metrika_goals, interests));
    }

    private Set<RetargetingConditionsRetargetingConditionsType> convertTypes(List<RetargetingListTypeEnum> types) {
        return types.stream()
                .map(this::convertType)
                .collect(Collectors.toSet());
    }

    private RetargetingConditionsRetargetingConditionsType convertType(RetargetingListTypeEnum type) {
        switch (type) {
            case RETARGETING:
                return RetargetingConditionsRetargetingConditionsType.metrika_goals;
            case AUDIENCE:
                return RetargetingConditionsRetargetingConditionsType.interests;
            default:
                throw new IllegalArgumentException("RetargetingListTypeEnum: " + type);
        }
    }
}
