package com.webforest.sftswing;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashSet;
import java.util.Set;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

import com.dukascopy.api.IChart;
import com.dukascopy.api.Instrument;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ISystemListener;

@SpringBootApplication
public class SftswingApplication extends JFrame {

	private static String jnlpUrl = "http://platform.dukascopy.com/demo/jforex.jnlp";
	private static String userName = "DEMO2mwVTg";
	private static String password = "mwVTg";

	private static IClient client = null;
	private static int lightReconnects = 3;

	public SftswingApplication() {

		initUI();

	}

	private void abc() {
		try {
			client = ClientFactory.getDefaultInstance();

			setSystemListener();
			tryToConnect();

			Set<Instrument> set = new HashSet<>();
			set.add(Instrument.EURUSD);
			client.setSubscribedInstruments(set);

			System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA : " + client.isConnected());

		} catch (Exception e) {
			e.printStackTrace();
		}

		pqr();

	}

	private void pqr() {

		File file = new File("C:\\Users\\ADmin1\\Desktop\\eurusd.tmpl");

		System.out.println("file : " + file.getAbsolutePath());

		IChart chart = client.openChart(file);
		System.out.println("is live : " + chart.isAlive());

	}

	private static void setSystemListener() {
		// set the listener that will receive system events
		client.setSystemListener(new ISystemListener() {
			@Override
			public void onStart(long processId) {
				System.out.println("Strategy started: " + processId);
			}

			@Override
			public void onStop(long processId) {
				System.out.println("Strategy stopped: " + processId);
				if (client.getStartedStrategies().size() == 0) {
					System.exit(0);
				}
			}

			@Override
			public void onConnect() {
				System.out.println("Connected");
				lightReconnects = 3;
			}

			@Override
			public void onDisconnect() {
				tryToReconnect();
			}
		});
	}

	private static void tryToConnect() throws Exception {
		System.out.println("Connecting...");
		// connect to the server using jnlp, user name and password
		client.connect(jnlpUrl, userName, password);

		// wait for it to connect
		int i = 10; // wait max ten seconds
		while (i > 0 && !client.isConnected()) {
			Thread.sleep(1000);
			i--;
		}
		if (!client.isConnected()) {
			System.out.println("Failed to connect Dukascopy servers");
			System.exit(1);
		}
	}

	private static void tryToReconnect() {

		if (lightReconnects > 0) {
			client.reconnect();
			--lightReconnects;
		} else {
			do {
				try {
					Thread.sleep(60 * 1000);
				} catch (InterruptedException e) {
				}
				try {
					if (client.isConnected()) {
						break;
					}
					client.connect(jnlpUrl, userName, password);

				} catch (Exception e) {

					System.out.println("Error : " + e.getMessage());
				}
			} while (!client.isConnected());
		}
	}

	private void initUI() {

		JButton quitButton = new JButton("Login");

		quitButton.addActionListener((ActionEvent event) -> {
			abc();
			//System.exit(0);
		});

		createLayout(quitButton);

		setTitle("Quit button");
		setSize(300, 200);
		setLocationRelativeTo(null);
		//setDefaultCloseOperation(EXIT_ON_CLOSE);

		
	}

	private void createLayout(JComponent... arg) {

		var pane = getContentPane();
		var gl = new GroupLayout(pane);
		pane.setLayout(gl);

		gl.setAutoCreateContainerGaps(true);

		gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(arg[0]));

		gl.setVerticalGroup(gl.createSequentialGroup().addComponent(arg[0]));
	}

	public static void main(String[] args) {

		var ctx = new SpringApplicationBuilder(SftswingApplication.class).headless(false).run(args);

		EventQueue.invokeLater(() -> {

			var ex = ctx.getBean(SftswingApplication.class);
			ex.setVisible(true);
		});
	}
}
