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

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

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.info.HostDbHostInfo;
import ru.yandex.wmconsole.servantlet.WMCAuthorizedHostOperationServantlet;
import ru.yandex.wmconsole.service.HostDbHostInfoService;
import ru.yandex.wmconsole.service.WMCTopInfoService;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;

/**
 * @author avhaliullin
 */
public class AddMultipleCustomQueriesServantlet extends WMCAuthorizedHostOperationServantlet {
    private static final String PARAM_QUERIES = "queries";

    private WMCTopInfoService topInfoService;
    private HostDbHostInfoService hostDbHostInfoService;

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

        HostDbHostInfo hostDbHostInfo = hostDbHostInfoService.getHostDbHostInfo(
                getHostInfoAndVerify(req, userId).getName());
        String queries = getRequiredStringParam(req, PARAM_QUERIES);
        StringTokenizer st = new StringTokenizer(queries, "\n\r");

        List<String> queriesList = new ArrayList<String>();
        while (st.hasMoreTokens()) {
            String query = topInfoService.standardizeQuery(st.nextToken());
            if (!StringUtils.isEmpty(query)) {
                queriesList.add(query);
            }
        }
        if (!queriesList.isEmpty()) {
            topInfoService.addCustomQueriesForHost(hostDbHostInfo, queriesList);
        }
    }

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

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