import Six.Sixp.Client.IRequest;

import java.util.Hashtable;
import java.util.Vector;

/**
 * Created by IntelliJ IDEA.
 * User: jeda1
 * Date: 2013-12-18
 * Time: 10:15
 * To change this template use File | Settings | File Templates.
 */
public class RequestHandler
{
    private Vector<RequestItem> _originalRequests;
    private Vector<RequestItem> _requestPopList;
    private Hashtable<Integer,RequestItem> _requestIdToRequestItem;

    public RequestHandler()
    {
        _originalRequests=new Vector<RequestItem>(10);
        _requestPopList=new Vector<RequestItem>(10);
        _requestIdToRequestItem=new Hashtable<Integer,RequestItem>(10);
    }

    public synchronized void AddRequestItem(RequestItem ri)
    {
        _originalRequests.add(ri);
    }

    public synchronized void SetRequestOnRequestItem(RequestItem ri, IRequest r) throws Exception
    {
        if (!_originalRequests.contains(ri)) throw new Exception("Could not find RequestItem Prl=" + ri.getPrl());
        if (_requestIdToRequestItem.containsKey(r.getId())) throw new Exception("A RequestItem with key=" + r.getId() + " is already present");
        ri.setRequest(r);
        _requestIdToRequestItem.put(r.getId(),ri);


    }

    public synchronized RequestItem GetRequestItemByRequestId(int id)
    {
        if (!_requestIdToRequestItem.containsKey(id)) return null;
        return _requestIdToRequestItem.get(id);
    }


    public Boolean IsOkToExecuteAllAtOnce()
    {
        //If there is 30 or less request to subscribe, it's ok to do them all at once.
        //If more the 30, execute them one by one.
        //Tip: Change the value bellow (30) to a value that is less then the number of request created in
        //the constructor of the Demo class. This will demonstrate the one by one behaviour.

        return _originalRequests.size()<=2;
    }

    public synchronized void PrepareRequestItemPopList()
    {
        _requestPopList.clear();
        for(RequestItem ri: _originalRequests)
        {
            if (ri.getRequest()!=null) ri.getRequest().Dispose();
            ri.setRequest(null);
            _requestPopList.add(ri);
        }
    }

    public synchronized RequestItem PopRequestItem()
    {

        if (_requestPopList.size()==0) return null;
        RequestItem ri=_requestPopList.elementAt(0);
        _requestPopList.remove(0);
        return ri;
    }

}
