package ru.yandex.wmconsole.servantlet.sitemaps;

import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.webmaster.viewer.service.NewWebmasterProxyService;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.SitemapInfo;
import ru.yandex.wmconsole.data.wrappers.SitemapInfoWrapper;
import ru.yandex.webmaster.common.sitemap.SitemapService;
import ru.yandex.wmconsole.servantlet.WMCAuthorizedHostOperationServantlet;
import ru.yandex.wmconsole.util.HostElementWrapper;
import ru.yandex.wmconsole.viewer.sitemap.SitemapService2;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;

public class AddSitemapServantlet extends WMCAuthorizedHostOperationServantlet {
    private static final Logger log = LoggerFactory.getLogger(AddSitemapServantlet.class);

    private static final String PARAM_URL = "url";

    private SitemapService sitemapService;
    private SitemapService2 sitemapService2;
    private NewWebmasterProxyService newWebmasterProxyService;

    @Override
    public void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        log.debug("AddSitemap: Started");

        BriefHostInfo briefHostInfo = getHostInfoAndVerify(req, userId);
        URL sitemapUrl = prepareUrl(getRequiredStringParam(req, PARAM_URL), true);
        try {
            sitemapService2.getAndValidateSitemap(sitemapUrl);
        } catch (UserException e) {
            throw new UserException(e.getProblem(), e.getMessage(), e, PARAM_URL, sitemapUrl.toString());
        }
        log.debug("Adding sitemap for host " + briefHostInfo.getId() + ": " + sitemapUrl);
        SitemapInfo info = sitemapService.addSitemap(userId, req.getUserId(), briefHostInfo, sitemapUrl);
        try {
            newWebmasterProxyService.addSitemap(briefHostInfo, userId, sitemapUrl.toExternalForm());
        } catch (InternalException e) {
            log.error("Failed to add sitemap " + sitemapUrl + " for host " + briefHostInfo.getName() + " to new WM", e);
        }
        res.addData(new HostElementWrapper(new SitemapInfoWrapper(info), briefHostInfo));
        log.debug("AddSitemap: Finished");
    }

    @Required
    public void setSitemapService(SitemapService sitemapService) {
        this.sitemapService = sitemapService;
    }

    @Required
    public void setSitemapService2(SitemapService2 sitemapService2) {
        this.sitemapService2 = sitemapService2;
    }

    @Required
    public void setNewWebmasterProxyService(NewWebmasterProxyService newWebmasterProxyService) {
        this.newWebmasterProxyService = newWebmasterProxyService;
    }
}
