package ru.yandex.wmconsole.servantlet;

import java.net.URL;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.wmconsole.data.SearchDomainEnum;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.service.PublicReindexUrlService;
import ru.yandex.wmconsole.service.ReindexUrlService;
import ru.yandex.wmconsole.service.error.WMCUserProblem;
import ru.yandex.wmtools.common.SupportedProtocols;
import ru.yandex.wmtools.common.data.wrappers.SimpleWrapper;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;

/**
 * Пока не запущено. Ждем решения проблем с быстроботом.
 *
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class PublicReindexUrlServantlet extends WMCAuthorizedHostOperationServantlet {
    private static final String PARAM_URL = "url";
    private static final String PARAM_DO = "do";
    private static final String PARAM_DO_REINDEX = "reindex";

    private ReindexUrlService reindexUrlService;
    private PublicReindexUrlService publicReindexUrlService;

    private int maxRequestPerDay;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        String urlString = getStringParam(req, PARAM_URL);
        String doString = getStringParam(req, PARAM_DO);

        BriefHostInfo hostInfo = getHostInfoAndVerify(req, userId);

        try {
            if (!StringUtils.isEmpty(urlString) && PARAM_DO_REINDEX.equals(doString)) {
                URL url = prepareUrl(urlString, true);

                String urlHost = SupportedProtocols.getCanonicalHostname(url);
                urlHost = bringToStandardWwwPrefix(urlHost, hostInfo.getName());

                if (!urlHost.equalsIgnoreCase(hostInfo.getName())) {
                    throw new UserException(WMCUserProblem.HOST_NOT_OWNED_BY_USER,
                            "User does not own host or host is not present in database");
                }

                if (!reindexUrlService.isIndexed(url)) {
                    throw new UserException(WMCUserProblem.URL_IS_NOT_INDEXED, "Url " + url + " is not indexed.");
                }

                if (!publicReindexUrlService.isLimitExceededAndIncrement(hostInfo.getId())) {
                    reindexUrlService.reindexUrl(url, userId, SearchDomainEnum.RU);
                } else {
                    throw new UserException(WMCUserProblem.PUBLIC_REINDEXURL_HOST_LIMIT_EXCEEDED,
                            "Max host reindex urls per day limit exceeded");
                }
            }
        } finally {
            res.addData(new SimpleWrapper<String>(
                    Integer.toString(publicReindexUrlService.getRequestsCount(hostInfo.getId())),
                    "requests-for-host"));
            res.addData(new SimpleWrapper<Integer>(maxRequestPerDay, "max-requests"));
        }
    }

    @Required
    public void setReindexUrlService(ReindexUrlService reindexUrlService) {
        this.reindexUrlService = reindexUrlService;
    }

    @Required
    public void setPublicReindexUrlService(PublicReindexUrlService publicReindexUrlService) {
        this.publicReindexUrlService = publicReindexUrlService;
    }

    @Required
    public void setMaxRequestPerDay(int maxRequestPerDay) {
        this.maxRequestPerDay = maxRequestPerDay;
    }
}
