package ch.unisg.tapas.auctionhouse.domain;

import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lombok.Getter;

public class AuctionHouseDiscovery {

    private static final AuctionHouseDiscovery auctionHouseDiscovery = new AuctionHouseDiscovery();

    private final List<String> tasktypes = new ArrayList<String>() {
        {
            add("computation");
            add("smallrobot");
        }
    };

    @Getter
    private List<AuctionHouseDiscoveryInformation> auctionHouseDiscoveryList = new ArrayList<>() {
    };

    private AuctionHouseDiscovery() {
        try {
            // Add our information to list
            auctionHouseDiscoveryList.add(new AuctionHouseDiscoveryInformation(
                new AuctionHouseDiscoveryInformation.AuctionHouseUri(new URI("http://localhost:8086")),
                new AuctionHouseDiscoveryInformation.WebSubUri(new URI("http://localhost:8086/websub")),
                new AuctionHouseDiscoveryInformation.TaskTypes(tasktypes),
                new AuctionHouseDiscoveryInformation.TimeStamp(new Timestamp(new Date().getTime())),
                new AuctionHouseDiscoveryInformation.GroupName("Group 1")
                ));
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static AuctionHouseDiscovery getInstance() {
        return auctionHouseDiscovery;
    }

    public List<AuctionHouseDiscoveryInformation> getAuctionHouseDiscoveryInformation() {
        return auctionHouseDiscoveryList;
    }

    public void addAuctionHouseDiscoveryInformation(List<AuctionHouseDiscoveryInformation> informations) {

        outerloop:
        for (AuctionHouseDiscoveryInformation discovery : informations) {
            for (AuctionHouseDiscoveryInformation endpoint : auctionHouseDiscoveryList) {
                // Check if discovery is already in our discovery list
                if (endpoint.getAuctionHouseUri().getValue().toString().equals(discovery.getAuctionHouseUri().getValue().toString())) {
                    // Check if the new discovery is more recent than the current
                    if (endpoint.getTimeStamp().getValue().before(discovery.getTimeStamp().getValue())) {
                        // Endpoint information is older. Remove and add the new discovery to the list
                        auctionHouseDiscoveryList.remove(endpoint);
                        break;
                    } else {
                        continue outerloop;
                    }
                }
            }
            auctionHouseDiscoveryList.add(discovery);
        }

    }

}
