package ru.yandex.wmconsole.servantlet.api.delegate;

import java.io.IOException;

import org.jdom.Document;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.common.framework.pager.Pager;
import ru.yandex.webmaster.common.urltree.YandexSearchShard;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.HostDbHostInfo;
import ru.yandex.wmconsole.error.ClientException;
import ru.yandex.wmconsole.servantlet.xmlsearch.IndexUrlsServantlet;
import ru.yandex.wmconsole.service.LinkType;
import ru.yandex.wmtools.common.data.wrappers.SimpleWrapper;
import ru.yandex.wmtools.common.data.xmlsearch.XmlSearchRequest;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.InternalProblem;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.util.TimeFilter;

/**
 * @author ailyin
 */
public class ApiIndexUrlsDelegate extends IndexUrlsServantlet implements DelegateServantlet {
    private static final String NO_PATH = "*";
    private static final String INDEX_COUNT_FORMAT_STRING = "<index-count>%d</index-count>";

    @Override
    public void doProcess(ServRequest req, ServResponse res, long userId) throws ClientException, InternalException {

        BriefHostInfo hostInfo = getHostInfo(req, false, userId, true, true, res, false, false);

        Pager pager = new Pager(0, 100);

        TimeFilter noneTimeFilter = prepareTimeFilter(7);

        XmlSearchRequest request;
        try {
            request = createRequest(hostInfo.getName(), NO_PATH, noneTimeFilter, pager, req);
        } catch (UserException e) {
            //todo (minor) right solution here is to remove UserException from HostPathRequest signature
            throw new RuntimeException("wrong path has been passed", e);
        }

        Document response = getIndexInfoService().callXMLSearch(request);

        try {
            String resultString = createResultString(response, null);

            HostDbHostInfo hostDbHostInfo = getHostDbHostInfoService().getHostDbHostInfo(hostInfo.getName());

            YandexSearchShard searchShard = tblUrlTreesDao.getOptimumShardId(hostDbHostInfo);
            Long indexCount = urlTreeService.getPreciseIndexCount(hostDbHostInfo, searchShard);
            try {
                if (indexCount == null) {
                    indexCount = linksCacheService.getLinksCountAndUpdateCache(
                            hostDbHostInfo, LinkType.INDEX_URLS, searchShard, false);
                }
            } catch (UserException e) {
                throw new InternalException(InternalProblem.INTERNAL_PROBLEM, "Unexpected UserException", e);
            }

            resultString = String.format(INDEX_COUNT_FORMAT_STRING, indexCount) + resultString;
            res.addData(new SimpleWrapper<String>(resultString, "host"));
        } catch (IOException e) {
            throw new InternalException(InternalProblem.PROCESSING_ERROR,
                    "Cannot convert result in AbstractXmlSearchServantlet!", e);
        }
    }

    @Override
    protected String getXslFileName() {
        return "/xsl/api_index_urls.xsl";
    }

    @Override
    protected boolean isAbsolutePath() {
        return true;
    }

    @Override
    protected boolean needPunycodeDomain() {
        return false;
    }

    @Override
    protected boolean needPunycodeHostName() {
        return false;
    }

    @Override
    public void delegateWork(ServRequest req, ServResponse res, long userId) throws ClientException, InternalException {
        doProcess(req, res, userId);
    }
}
