package mock.model;


import mock.exceptions.SourceIDAllocationException;

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

/**
 * This class is responsible for allocating boat source IDs for use in a race, upon request.
 */
public class SourceIdAllocator {


    /**
     * This list contains all unallocated source IDs.
     */
    List<Integer> unallocatedIDs = new ArrayList<>();


    /**
     * This list contains all allocated source IDs.
     */
    List<Integer> allocatedIDs = new ArrayList<>();


    /**
     * Creates a source ID allocator, using the given list of unallocated source IDs.
     * @param unallocatedIDs List of unallocated source IDs.
     */
    public SourceIdAllocator(List<Integer> unallocatedIDs) {
        //We need to copy the list.
        this.unallocatedIDs.addAll(unallocatedIDs);
    }


    /**
     * Allocates a source ID for a boat.
     * @return The allocated source ID.
     * @throws SourceIDAllocationException Thrown if we cannot allocate any more source IDs.
     */
    public synchronized int  allocateSourceID() throws SourceIDAllocationException {

        if (!unallocatedIDs.isEmpty()) {

            int sourceID = unallocatedIDs.remove(0);

            allocatedIDs.add(sourceID);

            return sourceID;

        } else {
            throw new SourceIDAllocationException("Could not allocate a source ID.");

        }
    }


    /**
     * Returns a source ID to the source ID allocator, so that it can be reused.
     * @param sourceID Source ID to return.
     */
    public void returnSourceID(Integer sourceID) {

        //We remove an Integer, not an int, so that we remove by value not by index.
        allocatedIDs.remove(sourceID);

        unallocatedIDs.add(sourceID);
    }
}
