package ru.yandex.webmaster3.storage.links;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.link.BrokenLinkSample;
import ru.yandex.webmaster3.storage.links.dao.IncomingBrokenLinkSamplesYDao;
import ru.yandex.webmaster3.storage.links.dao.InternalBrokenLinkSamplesYDao;
import ru.yandex.webmaster3.storage.links.dao.OutgoingBrokenLinkSamplesYDao;

import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author leonidrom
 */
@Component
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class BrokenLinkSamplesService {
    private static final int SAMPLES_LIMIT = 100;

    private final InternalBrokenLinkSamplesYDao internalBrokenLinkSamplesYDao;
    private final IncomingBrokenLinkSamplesYDao incomingBrokenLinkSamplesYDao;
    private final OutgoingBrokenLinkSamplesYDao outgoingBrokenLinkSamplesYDao;

    public List<BrokenLinkSample> getRecentSamplesForLinkType(WebmasterHostId hostId, BrokenLinkType linkType) {
        switch (linkType) {
            case INCOMING -> {
                return incomingBrokenLinkSamplesYDao.getRecentSamplesForDstHost(hostId, SAMPLES_LIMIT);
            }
            case OUTGOING -> {
                return outgoingBrokenLinkSamplesYDao.getRecentSamplesForSrcHost(hostId, SAMPLES_LIMIT);
            }
            case INTERNAL -> {
                return internalBrokenLinkSamplesYDao.getRecentSamplesForSrcHost(hostId, SAMPLES_LIMIT);
            }
        }

        return Collections.emptyList();
    }

    public long getSamplesCountForLinkType(WebmasterHostId hostId, BrokenLinkType linkType) {
        switch (linkType) {
            case INCOMING -> {
                return incomingBrokenLinkSamplesYDao.getSamplesCountForDstHost(hostId);
            }
            case OUTGOING -> {
                return outgoingBrokenLinkSamplesYDao.getSamplesCountForSrcHost(hostId);
            }
            case INTERNAL -> {
                return internalBrokenLinkSamplesYDao.getSamplesCountForSrcHost(hostId);
            }
        }

        return 0;
    }

    public void streamSamplesForLinkType(WebmasterHostId hostId, BrokenLinkType linkType,
                                                           Consumer<BrokenLinkSample> consumer) {
        switch (linkType) {
            case INCOMING -> {
                incomingBrokenLinkSamplesYDao.streamSamplesForDstHost(hostId, consumer);
            }
            case OUTGOING -> {
                outgoingBrokenLinkSamplesYDao.streamSamplesForSrcHost(hostId, consumer);
            }
            case INTERNAL -> {
                internalBrokenLinkSamplesYDao.streamSamplesForSrcHost(hostId, consumer);
            }
        }
    }
}
