package ru.yandex.webmaster3.viewer.http.checklist.extras;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemTypeEnum;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.storage.checklist.dao.MdbDomainsOnSearchCHDao;
import ru.yandex.webmaster3.storage.checklist.data.AbstractProblemInfo;
import ru.yandex.webmaster3.storage.checklist.service.SiteProblemsService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;

/**
 * @author akhazhoyan 08/2018
 */
@ReadAction
@Category("checklist")
@Description("Примеры поддоменов, которые есть на поиске, но не добавлены в вебмастер")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public final class DomainsOnSearchPageSamplesAction
        extends AbstractUserVerifiedHostAction<PageSamplesRequest, PageSamplesResponse> {
    private static final PageSamplesResponse EMPTY = new PageSamplesResponse(Collections.emptyList(), 0);
    private static final SiteProblemTypeEnum PROBLEM_TYPE = SiteProblemTypeEnum.TOO_MANY_DOMAINS_ON_SEARCH;

    private final SiteProblemsService siteProblemsService;
    private final MdbDomainsOnSearchCHDao mdbDomainsOnSearchCHDao;

    @Override
    public PageSamplesResponse process(PageSamplesRequest request) {
        WebmasterHostId hostId = request.getHostId();
        String ownerStr = hostId.getPunycodeHostname();

        AbstractProblemInfo problemInfo = siteProblemsService.getRealTimeProblemInfo(hostId, PROBLEM_TYPE);
        if (problemInfo == null || problemInfo.getState() == PROBLEM_TYPE.getDefaultState()) {
            return EMPTY;
        }
        int total = mdbDomainsOnSearchCHDao.countDomains(ownerStr);
        if (total == 0) {
            return EMPTY;
        }

        PageUtils.Pager pager = PageUtils.getPage(request.getP(), request.getPSize());
        List<PageSamplesResponse.PageSample> samples = mdbDomainsOnSearchCHDao
                .getDomainsWithPagination(ownerStr, pager.toRangeStart(), pager.getPageSize())
                .stream()
                .map(this::urlOrThrowUnchecked)
                .map(PageSamplesResponse.PageSample::new)
                .collect(Collectors.toList());
        return new PageSamplesResponse(samples, total);
    }

    private URL urlOrThrowUnchecked(String urlString) {
        try {
            return new URL(urlString);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
}
