package ru.yandex.wmconsole.servantlet;

import java.util.List;

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.NotificationMessageInfo;
import ru.yandex.wmconsole.data.wrappers.NotificationMessageWrapper;
import ru.yandex.wmconsole.service.MessageService;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.servantlet.AuthenticationServantlet;
import ru.yandex.wmtools.common.util.XmlConvertableCollectionWrapper;

/**
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class LastMessageWidget extends AuthenticationServantlet {
    private static final String PARAM_COUNT = "count";
    private static final int DEFAULT_MESSAGES_COUNT = 3;

    protected MessageService messageService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        Integer count = getIntParam(req, PARAM_COUNT);
        if (count == null) {
            count = DEFAULT_MESSAGES_COUNT;
        }
        List<NotificationMessageInfo> lastMessages = messageService.getLastMessages(userId, count);
        if (lastMessages != null) {
            res.addData(XmlConvertableCollectionWrapper.wrap(lastMessages, NotificationMessageWrapper.class, "last-messages"));
        }
    }

    @Required
    public void setMessageService(MessageService messageService) {
        this.messageService = messageService;
    }
}
