/*
 * Copyright 2012 IFH-InfoCentre, Ltd.
*/

package ru.mfd.api.examples;

import ru.mfd.api.SrvrSession;
import ru.mfd.api.SrvrSessionListener;
import ru.mfd.api.consts.LoginError;

import java.util.Arrays;

/**
 * User: MMarkelov
 * Date: 10.10.12
 * Time: 12:32
 */
public class ServerConnection {

	private static final String host = "nidemo.mfd.ru";
	private static final int port = 2900;
	private static final String login = "";
	private static final String password = "";
	private static final int connectionTimeout = 60000;

	private SrvrSessionListener listener;
	private SrvrSession srvrSession;

	private class Listener implements SrvrSessionListener {
		public void onLogin(int result, String description) {
			if (result == LoginError.LOGIN_SUCCESS)
				System.out.println("onLogin: success");
			else
				System.err.println("onLogin: failed [" + result + "] " + description);
		}

		public void onConnectionLost(String description) {
			System.err.println("onConnectionLost: " + description);
			try {
				Thread.sleep(1000);
				srvrSession.connect(host, port, login, password, listener, connectionTimeout);
			} catch (Exception ex) {
				System.err.println("Failed to reconnect: " + ex);
			}
		}

		public void onStatusMessage(int i, String[] s) {
			System.out.println("onStatusMessage: " + i + " " + Arrays.toString(s));
		}
	}

	private void run() {
		try {
			Runtime.getRuntime().addShutdownHook(new Thread() {
				public void run() {
					if (srvrSession != null) {
						srvrSession.disconnect();
					}
				}
			});

			listener = new Listener();
			srvrSession = new SrvrSession();
			srvrSession.connect(host, port, login, password, listener, connectionTimeout);
		} catch (Exception e) {
			System.err.println("Exception: " + e);
		}
	}

	public static void main(String[] args) throws Exception {
		System.out.println("ConnectionExample");
		System.out.println("Press ENTER to quit");
		ServerConnection example = new ServerConnection();
		example.run();
		System.in.read();
	}
}
