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

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.common.framework.pager.Pager;
import ru.yandex.wmconsole.data.DisplayNameModerationStateEnum;
import ru.yandex.wmconsole.data.info.DisplayNameModerationInfo;
import ru.yandex.wmconsole.data.wrappers.DisplayNameModerationInfoWrapper;
import ru.yandex.wmconsole.servantlet.WMCAuthenticationServantlet;
import ru.yandex.wmconsole.service.DisplayNameModerationService;
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 ailyin
 */
public class DisplayNameModerationHistoryServantlet 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_NAME = "name";

    private DisplayNameModerationService displayNameModerationService;

    @Override
    protected 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);
        }

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

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

        String name = getStringParam(req, PARAM_NAME);

        Collection<DisplayNameModerationInfo> moderationList =
                displayNameModerationService.getDisplayNameModerationHistory(moderatorId, pager, timeFilter, state, name);

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

    @Required
    public void setDisplayNameModerationService(DisplayNameModerationService hostNameService) {
        this.displayNameModerationService = hostNameService;
    }
}
