package ru.yandex.wmconsole.servantlet.moderation.regions;

import java.text.ParseException;
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.wmconsole.data.info.UserHostRegionInfo;
import ru.yandex.wmconsole.data.wrappers.UserHostRegionInfoWrapper;
import ru.yandex.wmconsole.servantlet.WMCAuthenticationServantlet;
import ru.yandex.wmconsole.service.HostRegionService;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.error.UserProblem;
import ru.yandex.wmtools.common.util.TimeFilter;
import ru.yandex.wmtools.common.util.XmlConvertableCollectionWrapper;

/**
 * @author baton
 */
public class HostRegionsWaitingListServantlet extends WMCAuthenticationServantlet {
    private static final String PARAM_DELAYED = "delayed";
    private static final String PARAM_URL = "url";
    private static final String PARAM_MODERATOR = "moderator";
    private static final String PARAM_AFTER = "after";
    private static final String PARAM_BEFORE = "before";

    private HostRegionService hostRegionService;

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

        Boolean delayed = getBooleanParam(req, PARAM_DELAYED);
        if (delayed == null) {
            delayed = false;
        }

        String urlTemplate = getStringParam(req, PARAM_URL);

        String after = getStringParam(req, PARAM_AFTER);
        String before = getStringParam(req, PARAM_BEFORE);
        TimeFilter timeFilter;
        try {
            timeFilter = TimeFilter.create(after, before, "yyyy/MM/dd");
        } catch (ParseException e) {
            throw new UserException(UserProblem.ILLEGAL_VALUE_TYPE, "failed to parse date", e);
        }

        String moderatorParam = getStringParam(req, PARAM_MODERATOR);
        Long moderatorId = (moderatorParam != null) ? getAndCheckUserIdByNameOrId(req, PARAM_MODERATOR) : null;

        Collection<UserHostRegionInfo> hostRegionsInfos = hostRegionService.getWaitingHosts(delayed, urlTemplate, timeFilter, moderatorId);
        int totalCount = hostRegionService.getWaitingHostsCount(delayed, urlTemplate, timeFilter, moderatorId);
        res.addData(
                XmlConvertableCollectionWrapper.wrap(
                        hostRegionsInfos,
                        UserHostRegionInfoWrapper.class,
                        "waiting-list", "total-count", Integer.toString(totalCount)
                )
        );
    }

    @Required
    public void setHostRegionService(HostRegionService hostRegionService) {
        this.hostRegionService = hostRegionService;
    }
}
