package ru.yandex.wmconsole.servantlet.top.queries;

import java.util.Collection;

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.framework.pager.Pager;
import ru.yandex.common.util.db.OrderByClause;
import ru.yandex.wmconsole.data.info.HostDbHostInfo;
import ru.yandex.wmconsole.data.wrappers.CustomQueryInfoWrapper;
import ru.yandex.wmconsole.servantlet.WMCAuthorizedHostOperationServantlet;
import ru.yandex.wmconsole.service.HostDbHostInfoService;
import ru.yandex.wmconsole.service.WMCTopInfoService;
import ru.yandex.wmtools.common.data.info.CustomQueryInfo;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.util.XmlConvertableCollectionWrapper;

public class CustomQueryListServantlet extends WMCAuthorizedHostOperationServantlet {
    private WMCTopInfoService topInfoService;
    private HostDbHostInfoService hostDbHostInfoService;

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

        HostDbHostInfo hostDbHostInfo = hostDbHostInfoService.getHostDbHostInfo(getHostInfoAndVerify(req, userId).getName());
        Pager pager = createOutputStrategy(req).createPager();
        OrderByClause order = new OrderByClause("q.query", !"desc".equals(req.getParam("order_by_mode")));
        Collection<CustomQueryInfo> customQueryInfos = topInfoService.getCustomQueriesForHost(hostDbHostInfo, order, pager);

        res.addData(XmlConvertableCollectionWrapper.wrap(customQueryInfos, CustomQueryInfoWrapper.class, "custom-queries"));
        res.addData(pager);
    }

    @Required
    public void setTopInfoService(WMCTopInfoService topInfoService) {
        this.topInfoService = topInfoService;
    }

    @Required
    public void setHostDbHostInfoService(HostDbHostInfoService hostDbHostInfoService) {
        this.hostDbHostInfoService = hostDbHostInfoService;
    }
}
