package ru.yandex.wmconsole.notifier.sender;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.wmconsole.data.NotificationChannelEnum;
import ru.yandex.wmconsole.data.NotificationsForUser;
import ru.yandex.wmconsole.service.MessageService;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class MessageNotificationSender extends AbstractSender {
    private static final Logger log = LoggerFactory.getLogger(MessageNotificationSender.class);

    private MessageService messageService;

    @Override
    public boolean sendPortionToUser(NotificationsForUser notificationsForUser, Integer notificationType) {
        String message;
        try {
            message = extractXmlString(notificationsForUser, NotificationChannelEnum.MESSAGE, false);
        } catch (Exception e) {
            log.error("Exception while sending message", e);
            return false;
        }

        Long userId = notificationsForUser.getUserId();

        try {
            messageService.sendMessageToUser(userId, message, notificationType);
            return true;
        } catch (InternalException e) {
            log.error("InternalException in " + getClass().getName(), e);
            return false;
        }
    }

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