package ru.yandex.webmaster3.storage.checklist.dao;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.checklist.data.MicrodataDocStatus;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;


/**
 * Урлы хранятся <strong>относительные</strong>.
 *
 * @author avhaliullin
 */
@Repository
public class MicrodataErrorSamplesYDao extends AbstractYDao {
    public MicrodataErrorSamplesYDao() {
        super(PREFIX_WEBMASTER3, "microdata_error_samples");
    }

    public Map<MicrodataDocStatus, List<String>> getSamples(WebmasterHostId hostId) {
        return select(F.status.combine(F.samples, Pair::of))
                .where(F.hostId.eq(hostId))
                .queryForList().stream().collect(
                        Collectors.toMap(Pair::getKey, Pair::getValue, (u, v) -> {
                                    throw new IllegalStateException("Duplicate keys found");
                                },
                                () -> new EnumMap<>(MicrodataDocStatus.class)));
    }

    private static class F {
        static final Field<WebmasterHostId> hostId = Fields.hostIdField("host_id");
        static final Field<MicrodataDocStatus> status = Fields.intEnumField("status", MicrodataDocStatus.R);
        static final Field<List<String>> samples = Fields.jsonField("samples", new TypeReference<List<String>>() {
        });
    }
}
