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

import java.util.Collection;
import java.util.Map;
import java.util.Objects;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import javax.xml.bind.JAXBElement;

import com.google.common.collect.ImmutableMap;
import com.yandex.direct.api.v5.ads.AdCategoryEnum;
import com.yandex.direct.api.v5.ads.ArrayOfAdCategoryEnum;
import com.yandex.direct.api.v5.ads.ObjectFactory;

import ru.yandex.direct.core.entity.banner.model.BannerFlags;

import static java.util.stream.Collectors.toList;

@ParametersAreNonnullByDefault
public class CategoriesConverter {

    private static final ObjectFactory FACTORY = new ObjectFactory();

    public static final Map<String, AdCategoryEnum> CATEGORIES =
            ImmutableMap.<String, AdCategoryEnum>builder()
                    .put(BannerFlags.ABORTION.getKey(), AdCategoryEnum.ABORTION)
                    .put(BannerFlags.ALCOHOL.getKey(), AdCategoryEnum.ALCOHOL)
                    .put(BannerFlags.BABY_FOOD.getKey(), AdCategoryEnum.BABY_FOOD)
                    .put(BannerFlags.DIETARYSUPPL.getKey(), AdCategoryEnum.DIETARY_SUPPLEMENTS)
                    .put(BannerFlags.MEDICINE.getKey(), AdCategoryEnum.MEDICINE)
                    .put(BannerFlags.MED_SERVICES.getKey(), AdCategoryEnum.MEDICINE)
                    .put(BannerFlags.MED_EQUIPMENT.getKey(), AdCategoryEnum.MEDICINE)
                    .put(BannerFlags.PHARMACY.getKey(), AdCategoryEnum.MEDICINE)
                    .put(BannerFlags.PROJECT_DECLARATION.getKey(), AdCategoryEnum.PROJECT_DECLARATION)
                    .put(BannerFlags.PSEUDOWEAPON.getKey(), AdCategoryEnum.PSEUDO_WEAPON)
                    .put(BannerFlags.TOBACCO.getKey(), AdCategoryEnum.TOBACCO)
                    .build();


    static JAXBElement<ArrayOfAdCategoryEnum> convertCategories(@Nullable BannerFlags bannerFlags) {
        Collection<AdCategoryEnum> result = null;

        if (bannerFlags != null) {
            result = bannerFlags.getFlags().keySet().stream().map(CATEGORIES::get).filter(Objects::nonNull).distinct()
                    .sorted().collect(toList());
        }

        return FACTORY.createAdGetItemAdCategories(
                result == null || result.isEmpty() ? null : new ArrayOfAdCategoryEnum().withItems(result));
    }
}
