/**
 */
import Six.Sixp.Client.*;
import sun.awt.windows.ThemeReader;

import java.util.Vector;


public class RequestEventListener implements IRequestEventListener
{

    private RequestHandler _requestHandler;
    private ISession _sess;

    public RequestEventListener(RequestHandler requestHandler)
    {
        _requestHandler=requestHandler;
    }

    public void SetSession(ISession sess)
    {
        _sess=sess;
    }

    public void OnInitTable(IRequest iRequest, int i)
    {
        //This method gets called when a request has executed successfully and the
        //initial snapshot data will follow.

        System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnInitTable Id=" + iRequest.getId() + " num rows=" + i);

        RequestItem ri=_requestHandler.GetRequestItemByRequestId(iRequest.getId());
        ri.setTableFilled(false); //Set this to indicate that we are receiving initial data and that we don't
                                  // want to log all initial updates
    }

    public void OnTableFilled(IRequest iRequest)
    {
        //This method gets called when the initial snapshot data for the request is transferred to the client.
        //From now on any call to OnRecordUpdate will be a new update.

        System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnTableFilled Id=" + iRequest.getId());

        RequestItem ri=_requestHandler.GetRequestItemByRequestId(iRequest.getId());
        ri.setTableFilled(true); //Set this to indicate that we are done receiving initial data and that we will
                                  // start to log all updates

        if (!_requestHandler.IsOkToExecuteAllAtOnce())
        {
            try
            {
                ri=_requestHandler.PopRequestItem();
                if (ri!=null)
                {
                    System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnTableFilled Executing next: " + ri.getPrl());
                    IRequest r=_sess.CreateRequest(ri.getPrl(),ri.getFormat(),ri.getSubscribe(),ri.getEventListener());
                    _requestHandler.SetRequestOnRequestItem(ri,r);
                    r.ExecuteAsync();
                }
                else
                {
                    System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnTableFilled No more request to execute");
                }
            }
            catch (Exception e)
            {
                System.out.println("RequestEventListener.OnTableFilled: " + e.getMessage());
            }
        }
    }

    public void OnRecordUpdate(IRequest iRequest, Vector<Update> updates)
    {
        //This method gets called when there are at least one update to process
        //Please note: The Update.GetKey() contains a key that is unique for the requested table.
        //A table is /rt/stock, /rt/index and so on. You should use the table and GetKey together
        //to build a key that is unique system wide. The key will also be valid from session to session
        //and between different SIXP servers. Use this approach.

        //We have seen cases where GetRecordId() have been used as key and this is not a good solution.
        //The record id is only used to identify a record within the request.


        RequestItem ri=_requestHandler.GetRequestItemByRequestId(iRequest.getId());
        if (ri.getTableFilled())
        {
            //We have gotten the initial data, now start to log updates
            for (Update u:updates)
            {
                System.out.println(Demo.GetDateTimeString() + "request id=" + iRequest.getId()+ " Key: " +  u.GetKey() + " num updated fields:" + u.GetFields().length);
            }
        }

    }

    public void OnClearTable(IRequest iRequest)
    {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    public void OnError(IRequest iRequest, Six.Sixp.Client.Error error, String s)
    {
        //This will get called when the request executed with an error.
        //This could happen for several reasons. Malformed Prl, your account may not have
        //access to the information requested.
        //The main thing is that you should treat this as it was just the supplied request
        //that failed and act accordingly. If there is a bigger problem, such as a network
        //problem, you will get a call to OnDisconnected on the ISession instance (it may
        //be preceded with a call to OnError on ISession instance, depending of the error).

        System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnError (" + error +") " + s);

        //This means that if you have more requests left that you want to execute
        // one by one, continue to do so
        if (!_requestHandler.IsOkToExecuteAllAtOnce())
        {
            try
            {
                RequestItem ri=_requestHandler.PopRequestItem();
                if (ri!=null)
                {
                    System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnError Executing next: " + ri.getPrl());
                    IRequest r=_sess.CreateRequest(ri.getPrl(),ri.getFormat(),ri.getSubscribe(),ri.getEventListener());
                    _requestHandler.SetRequestOnRequestItem(ri,r);
                    r.ExecuteAsync();
                }
                else
                {
                    System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnError No more request to execute");
                }
            }
            catch (Exception e)
            {
                System.out.println("RequestEventListener.OnError: " + e.getMessage());
            }
        }

    }

    public void OnFieldSetReceived(IRequest iRequest, FieldInfoSet fieldInfoSet)
    {
        //This method is called when a request is executed ok.
        //FieldInfoSet contains a vector with field information for the fields that
        //will be updated. The field information for a specific field will also be present in the Field class (See Update class).
        //Normally you probably won't need to act upon this event.

        //It can be used to dynamically set up data sets or database tables.
        //NOTE: If you use FieldInfoSet and stores references to it you MUST discard these if you get disconnected and then
        //reconnects. The next session might connect to a different SIXP server and the FieldInfoSet for a certain request
        //might differ between two SIXP servers.

        System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnFieldSetReceived");
    }

    public void OnText(IRequest iRequest, String s)
    {
        System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnText: " + s);
        if (!_requestHandler.IsOkToExecuteAllAtOnce())
        {
            try
            {
                RequestItem ri=_requestHandler.PopRequestItem();
                if (ri!=null)
                {
                    System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnText Executing next: " + ri.getPrl());
                    IRequest r=_sess.CreateRequest(ri.getPrl(),ri.getFormat(),ri.getSubscribe(),ri.getEventListener());
                    _requestHandler.SetRequestOnRequestItem(ri,r);
                    r.ExecuteAsync();
                }
                else
                {
                    System.out.println(Demo.GetDateTimeString() + " RequestEventListener.OnText No more request to execute");
                }
            }
            catch (Exception e)
            {
                System.out.println("RequestEventListener.OnText: " + e.getMessage());
            }
        }

    }

    public void OnDestroyed(IRequest iRequest)
    {
        //The request has been destroyed. Remove any references to the request instance.
    }
}
