package ru.yandex.wmconsole.servantlet.all.about.url;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.common.framework.pager.Pager;
import ru.yandex.common.util.db.OrderByClause;
import ru.yandex.webmaster.viewer.view.all.about.url.UrlListView;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.all.about.url.ShortUrlInfo;
import ru.yandex.wmconsole.data.info.all.about.url.UrlRequestId;
import ru.yandex.wmconsole.util.XmlUtil;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.InternalProblem;
import ru.yandex.wmtools.common.error.UserException;

import javax.xml.bind.JAXBException;
import java.util.List;

/**
 * User: azakharov
 * Date: 15.10.13
 * Time: 19:14
 */
public class UrlInfoHistoryServantlet extends AbstractAllAboutUrlServantlet {

    private static final String PARAM_OMIT_SELECTED = "omit-selected";

    @Override
    protected void processUrlRequest(ServRequest req, ServResponse res, long userId, BriefHostInfo hostInfo) throws InternalException, UserException {

        UrlRequestId reportId = getRequestId(req);
        OrderByClause orderBy = getOrderByClause(req);
        boolean omitSelected = getBooleanParam(req, PARAM_OMIT_SELECTED, false);

        List<ShortUrlInfo> urls = getAllAboutUrlService().getUrlInfoHistory(hostInfo, reportId, orderBy, getFromSupport());

        ShortUrlInfo selected = null;
        for (ShortUrlInfo url : urls) {
            if (url.getRequestId().getId() == reportId.getId()) {
                selected = url;
                break;
            }
        }
        if (selected != null) {
            if (omitSelected) {
                urls.remove(selected);
            } else {
                selected.setSelected(true);
            }
        }

        // учитываем разбивку на страницы
        Pager pager = createOutputStrategy(req).createPager();
        pager.setCount(urls.size());
        urls = urls.subList(pager.getFrom() - 1, Math.min(pager.getTo(), urls.size()));

        // выводим результат
        try {
            res.addData(XmlUtil.xmlConvertable(new UrlListView(urls)));
            res.addData(pager);
        } catch (JAXBException e) {
            throw new InternalException(InternalProblem.INTERNAL_PROBLEM, "jaxb processing error", e);
        }
    }
}
