package com.arangodb.internal.net;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class HostSet {
    private static final Logger LOGGER = LoggerFactory.getLogger(HostSet.class);

    private final ArrayList<Host> hosts = new ArrayList<>();

    public HostSet() {
        super();
    }

    public HostSet(List<Host> hosts) {
        super();

        for (Host host : hosts) {
            addHost(host);
        }

    }

    public List<Host> getHostsList() {
        return Collections.unmodifiableList(hosts);
    }

    public void addHost(Host newHost) {

        if (hosts.contains(newHost)) {
            LOGGER.debug("Host" + newHost + " already in Set");

            for (Host host : hosts) {
                if (host.equals(newHost)) {
                    host.setMarkforDeletion(false);
                }
            }

        } else {
            hosts.add(newHost);
            LOGGER.debug("Added Host " + newHost + " - now " + hosts.size() + " Hosts in List");
        }

    }

    public void close() {
        LOGGER.debug("Close all Hosts in Set");

        for (Host host : hosts) {
            try {

                LOGGER.debug("Try to close Host " + host);
                host.close();

            } catch (IOException e) {
                LOGGER.warn("Error during closing the Host " + host, e);
            }
        }
    }

    public void markAllForDeletion() {

        for (Host host : hosts) {
            host.setMarkforDeletion(true);
        }

    }

    public void clearAllMarkedForDeletion() {

        LOGGER.debug("Clear all Hosts in Set with markForDeletion");

        for (Host host : hosts) {
            if (host.isMarkforDeletion()) {
                try {

                    LOGGER.debug("Try to close Host " + host);
                    host.close();

                } catch (IOException e) {
                    LOGGER.warn("Error during closing the Host " + host, e);
                }
            }
        }

    }

    public void clear() {
        LOGGER.debug("Clear all Hosts in Set");

        close();
        hosts.clear();
    }
}

@@ -173,16 +173,43 @@
 ctions;%0A
+import java.util.Iterator;%0A
 import j
@@ -1772,33 +1772,128 @@
     
-for (Host host : hosts) %7B
+Iterator%3CHost%3E iterable = hosts.iterator();%0A        while (iterable.hasNext())%7B%0A            Host host = iterable.next();
 %0A   
@@ -1947,33 +1947,32 @@
           try %7B%0A
-%0A
                 
@@ -2044,33 +2044,32 @@
   host.close();%0A
-%0A
                 
@@ -2086,32 +2086,32 @@
 OException e) %7B%0A
-
                 
@@ -2163,32 +2163,99 @@
 t %22 + host, e);%0A
+                %7D finally %7B%0A                    iterable.remove();%0A
                 

remove close host (#347)