package ru.yandex.wmconsole.notifier.provider;

import java.util.ArrayList;
import java.util.List;

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

import ru.yandex.wmconsole.data.GlobalMessageNotificationInfo;
import ru.yandex.wmconsole.data.NotificationChannelEnum;
import ru.yandex.wmconsole.data.info.NotificationInfo;
import ru.yandex.wmconsole.service.GlobalMessageService;
import ru.yandex.wmtools.common.error.InternalException;

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

    private GlobalMessageService globalMessageService;

    private static final String TAG_MESSAGE = "message";
    private static final String TAG_TITLE = "title";

//    @Override
//    public SendStrategy getSendStrategy() {
//        return DefaultSendStrategy.getInstance();
//    }

    @Override
    public List<Element> getNotificationElements(NotificationInfo notification, NotificationChannelEnum channel)
            throws InternalException {
        List<Element> elements = new ArrayList<Element>();
        try {
            GlobalMessageNotificationInfo globalMessage =
                    globalMessageService.getGlobalMessage(notification.getIssueId());
            elements.add(getMessageElement(globalMessage, channel));
            elements.add(getTitleElement(globalMessage));
        } catch (InternalException e) {
            log.error("InternalException in " + getClass().getName() + " while getting global message");
            throw e;
        }
        return elements;
    }

    private Element getMessageElement(GlobalMessageNotificationInfo globalMessage, NotificationChannelEnum channel) {
        Element element = new Element(TAG_MESSAGE);
        String message = globalMessage.getMessage();
        element.setText(message);
        return element;
    }

    private Element getTitleElement(GlobalMessageNotificationInfo globalMessage) {
        Element element = new Element(TAG_TITLE);
        element.setText(globalMessage.getHeader());

        return element;
    }

    @Required
    public void setGlobalMessageService(GlobalMessageService globalMessageService) {
        this.globalMessageService = globalMessageService;
    }
}
