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

import java.text.ParseException;
import java.util.Collection;

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.common.framework.pager.Pager;
import ru.yandex.wmconsole.data.HostRegionChangeRequestStateEnum;
import ru.yandex.wmconsole.data.info.RegionModerationHistoryInfo;
import ru.yandex.wmconsole.data.wrappers.RegionModerationHistoryInfoWrapper;
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;

public class RegionModerationHistoryServantlet extends WMCAuthenticationServantlet {
    private static final String PARAM_AFTER = "after";
    private static final String PARAM_BEFORE = "before";
    private static final String PARAM_MODERATOR = "moderator";
    private static final String PARAM_STATE = "state";
    private static final String PARAM_URL = "url";

    private HostRegionService hostRegionService;

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

        Pager pager = createOutputStrategy(req).createPager();

        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);
        }

        Long moderatorId = null;
        String moderatorParam = getStringParam(req, PARAM_MODERATOR);
        if (moderatorParam != null) {
            moderatorId = getAndCheckUserIdByNameOrId(req, PARAM_MODERATOR);
        }

        Integer intState = getIntParam(req, PARAM_STATE);
        HostRegionChangeRequestStateEnum state = (intState != null) ? HostRegionChangeRequestStateEnum.R.fromValueOrNull(intState) : null;

        String urlTemplate = StringUtils.trim(getStringParam(req, PARAM_URL));

        Collection<RegionModerationHistoryInfo> moderationList = hostRegionService.listRegionModerationHistory(moderatorId, pager, timeFilter, state, urlTemplate);

        res.addData(XmlConvertableCollectionWrapper.wrap(moderationList, RegionModerationHistoryInfoWrapper.class, "moderations"));
        res.addData(pager);
    }

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