package ru.yandex.wmconsole.notifier.provider.strategy;

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

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

import ru.yandex.wmconsole.data.GroupableByHostData;
import ru.yandex.wmconsole.data.info.NotificationInfo;
import ru.yandex.wmconsole.service.GroupableByHostService;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class ByHostIdStrategy<D extends GroupableByHostData> implements SendStrategy {
    private static final Logger log = LoggerFactory.getLogger(ByHostIdStrategy.class);

    private GroupableByHostService<D> service;

    @Override
    public List<NotificationInfo> getSendPortion(List<NotificationInfo> notifications) {
        try {
            List<NotificationInfo> result = new ArrayList<NotificationInfo>();
            List<NotificationInfo> toRemove = new ArrayList<NotificationInfo>();
            D hostIdHolder = null;
            for (NotificationInfo notification : notifications) {
                D singleNotificationInfo =
                        service.getSingleNotification(notification.getIssueId());
                if (hostIdHolder == null) {
                    hostIdHolder = singleNotificationInfo;
                    result.add(notification);
                    toRemove.add(notification);
                } else if (hostIdHolder.getHostId().equals(singleNotificationInfo.getHostId())) {
                    result.add(notification);
                    toRemove.add(notification);
                }
            }

            notifications.removeAll(toRemove);
            return result;
        } catch (InternalException e) {
            log.error("InternalException while trying to get notification info for send strategy", e);
            notifications.clear();
            return Collections.emptyList();
        }
    }

    @Required
    public void setService(GroupableByHostService<D> service) {
        this.service = service;
    }
}
