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.NotificationChannelEnum;
import ru.yandex.wmconsole.data.info.NotificationInfo;
import ru.yandex.wmconsole.service.HostInfoService;
import ru.yandex.wmconsole.service.HostUnavailableService;
import ru.yandex.wmtools.common.error.InternalException;

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

    private static final String TAG_HOST = "host";
    private static final String ATTRIBUTE_ID = "id";
    private static final String ATTRIBUTE_HOST_NAME = "name";

    private HostUnavailableService hostUnavailableService;
    private HostInfoService hostInfoService;

//    @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 {
            Long hostId =
                    hostUnavailableService.getHostUnavailable(notification.getIssueId());
            elements.add(getHostElement(hostId));
        } catch (InternalException e) {
            log.error("InternalException in " + getClass().getName() + " while getting host unavailable message");
            throw e;
        }
        return elements;
    }

    private Element getHostElement(Long hostId) throws InternalException {
        Element element = new Element(TAG_HOST);
        element.setAttribute(ATTRIBUTE_ID, hostId.toString());
        String hostName = hostInfoService.getHostNameByHostId(hostId);
        element.setAttribute(ATTRIBUTE_HOST_NAME, hostName);
        return element;
    }

    @Required
    public void setHostUnavailableService(HostUnavailableService hostUnavailableService) {
        this.hostUnavailableService = hostUnavailableService;
    }

    @Required
    public void setHostInfoService(HostInfoService hostInfoService) {
        this.hostInfoService = hostInfoService;
    }
}
