package ru.yandex.wmconsole.servantlet;

import java.util.ArrayList;
import java.util.List;

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.common.util.xml.XmlConvertable;
import ru.yandex.wmconsole.data.SearchDomainEnum;
import ru.yandex.wmconsole.data.info.AddUrlInfo;
import ru.yandex.wmconsole.data.wrappers.AddUrlInfoWrapper;
import ru.yandex.wmconsole.service.ReindexUrlService;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.servantlet.AuthenticationServantlet;
import ru.yandex.wmtools.common.util.XmlConvertableCollectionWrapper;

/**
 * Encodes urls using punycode and performs some checks.
 * Reports when urls are invalid.
 *
 * @author ailyin
 */
public class ReindexUrlServantlet extends AuthenticationServantlet {
    private static final Logger log = LoggerFactory.getLogger(ReindexUrlServantlet.class);

    private static final String PARAM_URLS = "urls";
    private static final String PARAM_SEARCH_DOMAIN = "search_domain";

    private ReindexUrlService reindexUrlService;

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

        String[] urls = splitInput(req.getParam(PARAM_URLS));
        SearchDomainEnum search = SearchDomainEnum.R.valueOfOrNull(req.getParam(PARAM_SEARCH_DOMAIN));

        List<XmlConvertable> results = new ArrayList<XmlConvertable>();
        for (String url : urls) {
            try {
                reindexUrlService.reindexUrl(doPrepareUrl(url, true, false), userId, search);
            } catch (UserException e) {
                results.add(new AddUrlInfoWrapper(new AddUrlInfo(url, e.getProblem().toString())));
            } catch (InternalException e) {
                results.add(new AddUrlInfoWrapper(new AddUrlInfo(url, e.getProblem().toString())));
            }
        }
        res.addData(new XmlConvertableCollectionWrapper(results, "reindexurl"));

        log.debug("ReindexUrl: Finished");
    }

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