package gethistprices;
import com.fxcore2.*;
import java.io.IOException;
import java.util.Scanner;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.Calendar;

public class Main {

        public static String strUserID = "";
        public static String strPassword = "";
        public static String strSessionId = "";
        public static String strPin = "";
        public static String strURL = "";
        public static String strConnection = "";
        public static int iMaxBars = 300;
        public static String strInstrument = "EUR/USD";
        public static String strTimeFrame = "m1";
        public static java.util.Calendar calenFrom = null;
        public static java.util.Calendar calenTo = null;
        public static Scanner sc = new Scanner(System.in);
        private static EventPipe mEventPipe = null;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        if (args.length < 4)
        {
            System.out.println("Not Enough Parameters!");
            System.out.println("USAGE: [user ID] [password] [URL] [connection] [session ID (if needed) or space (\" \")] [pin (if needed) or space (\" \")] [instrument (default \"EUR/USD\"] [time frame (default \"m1\")] [datetime \"from\" (YYYY-MM-dd hh:mm:ss) or space (\" \") for \"from now\" (default)] [datetime \"to\" (YYYY-MM-dd hh:mm:ss) or space (\" \") for \"to now\" (default)] [max number of bars (default 300)]");
            System.out.println("\nPress any key to close the program");
            sc.next();
            return;
        }
        strUserID = args[0];
        strPassword = args[1];
        strURL = args[2];
        strConnection = args[3];
        if (args.length > 4)
        {
            strSessionId = args[4].trim();
        }
        if (args.length > 5)
        {
            strPin = args[5].trim();
        }
        if (args.length > 6)
        {
            strInstrument = args[6];
        }
        if (args.length > 7)
        {
            strTimeFrame = args[7];
        }
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (args.length > 8)
        {
                    String strDateTimeFrom = args[8].trim();
                    try
                    {
                        if (!strDateTimeFrom.equals(""))
                        {
                            Date dtFrom = df.parse(strDateTimeFrom);
                            if (dtFrom != null)
                            {
                                calenFrom = Calendar.getInstance();
                                calenFrom.setTime(dtFrom);
                            }
                        }
                    }
                    catch (java.lang.Exception e)
                    {
                            calenFrom = null;
                    }
        }
        if (args.length > 9)
        {
                    String strDateTimeTo = args[9].trim();
                    try
                    {
                        if (!strDateTimeTo.equals(""))
                        {
                            Date dtTo = df.parse(strDateTimeTo);
                            if (dtTo != null)
                            {
                                calenTo = Calendar.getInstance();
                                calenTo.setTime(dtTo);
                            }
                        }
                    }
                    catch (java.lang.Exception e2)
                    {
                            calenTo = null;
                    }
        }
        if (args.length > 10)
        {
                    String strMaxBars = args[10];
                    try
                    {
                        iMaxBars = Integer.parseInt(strMaxBars);
                    }
                    catch (java.lang.Exception e3)
                    {
                        iMaxBars = 300;
                    }
        }

        try
        {
                    Runtime.getRuntime().addShutdownHook(new Thread() {
                        public void run() {
                            mEventPipe.putEvent(EventType.TERMINATE);
                        }
                    });
                    mEventPipe = new EventPipe();
                    LoginInfo loginInfo = null;
                    loginInfo = new LoginInfo(strUserID, strPassword, strURL, strConnection, strSessionId, strPin);
                    login(loginInfo);
    
        }
        catch (RuntimeException e)
        {
            System.out.println("Exception: " + e.toString());
        }
    }

        private static void login(LoginInfo loginInfo) {

        // "How to login" : Create session.
        O2GSession session = O2GTransport.createSession();
        SimpleLog simpleLog = null;
        try {
            simpleLog = new SimpleLog(String.format("%s.log", loginInfo.getUsername()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        simpleLog.log("Connecting to {0}", loginInfo.toString());

        // "How to login" : Create an instance of session status listener.
        SessionStatusListener sessionStatusListener = new SessionStatusListener(session, simpleLog, loginInfo.getTradingSessionID(), loginInfo.getTradingSessionPIN(), mEventPipe);

        // "How to login" : Subscribe status listener object to session status.
        session.subscribeSessionStatus(sessionStatusListener);

        // "How to login" : Create an instance of session response listener.
        ConcurrentLinkedQueue<O2GResponse> responseQueue = new ConcurrentLinkedQueue<O2GResponse>();

        ResponseListener responseListener = new ResponseListener(simpleLog, responseQueue, mEventPipe);

        // "How to login" : Subscribe response listener object to session response.
        session.subscribeResponse(responseListener);

        // "How to login" : The events are coming asynchronously.
        //                  They should come in another thread.
        //                  When the event will come, the signal will be sent to the main thread.

        EventListener eventListener = new EventListener(simpleLog, responseQueue, session, mEventPipe);

        // "How to login" : Login using user ID, password, URL, and connection.
        session.login(loginInfo.getUsername(), loginInfo.getPassword(), loginInfo.getConnection(), loginInfo.getConnectionName());
                
        eventListener.waitNextEvent();

        // "How to login" : Unsubscribe session from status listener.
        session.unsubscribeSessionStatus(sessionStatusListener);

        // "How to login" : Unsubscribe session from response listener.
        session.unsubscribeResponse(responseListener);

        session.dispose();
    }

}
