// ***** Amended version with policy prefetch at end of Awake () for SFS 1.x
//          Needs compatible SmartFoxClient.dll for SFS 1.x
//          Example from http://www.smartfoxserver.com/forums/viewtopic.php?p=41732
//          Comment by lastowl who provides "Island Demo using SFS 1" at
//          http://unity.lastowl.info/IslandDemo3.0.zip 
//         Change List: 
//                   Not much changed two lines of code are nulled not removed 
//                   Policy Fetch Added for web player builds 
//                   Assets/Plugins/SmartFoxClient.dll  replaced as well 

using UnityEngine;
using System;
using System.Collections;
using SmartFoxClientAPI;
using SmartFoxClientAPI.Data;
using SmartFoxClientAPI.Util;

public class LoginGUI : MonoBehaviour {
	private SmartFoxClient smartFox;
	private bool shuttingDown = false;

	private string serverIP = "129.215.219.144";
	private string serverPort = "9339";
	public string zone = "simpleChat";
	public bool debug = true;

	public GUISkin gSkin;

	private string username = "";
	private string loginErrorMessage = "";

	/************
     * Unity callback methods
     ************/

	void OnApplicationQuit() {
		shuttingDown = true;
	}

	private bool connectionAttempt = false;

	void Awake() {
		Application.runInBackground = true;

		if ( SmartFox.IsInitialized() ) {
			smartFox = SmartFox.Connection;
		} else {
			try {
				smartFox = new SmartFoxClient(debug);
				smartFox.runInQueueMode = true;
			} catch ( Exception e ) {
				loginErrorMessage = e.ToString();
			}
		}

		// Register callback delegate
		SFSEvent.onConnection += OnConnection;
		SFSEvent.onConnectionLost += OnConnectionLost;
		SFSEvent.onLogin += OnLogin;
		SFSEvent.onRoomListUpdate += OnRoomList;
		SFSEvent.onDebugMessage += OnDebugMessage;
		
		// ***** ADDED for SFS 1.x SmartFox Server 1.x - Policy
		Security.PrefetchSocketPolicy(serverIP, Convert.ToInt32(serverPort));

	}
	
	void FixedUpdate() {
		smartFox.ProcessEventQueue();
	}

	void OnGUI() {

		GUI.skin = gSkin;
		GUI.Label(new Rect(2, -2, 680, 70), "", "SFSLogo");	
		//connectionAttempt = true;
	    //smartFox.Connect(serverIP, Convert.ToInt32(serverPort));

		if (!connectionAttempt) {
			GUI.Label(new Rect(10, 116, 100, 100), "IP: ");
			serverIP = GUI.TextField(new Rect(100, 116, 200, 20), serverIP, 25);
			
			GUI.Label(new Rect(10, 136, 100, 100), "Port: ");
			serverPort = GUI.TextField(new Rect(100, 136, 200, 20), serverPort, 25);
			
			if (GUI.Button(new Rect(100, 166, 100, 24), "Connect")  || (Event.current.type == EventType.keyDown && Event.current.character == '\n')) {
				connectionAttempt = true;
				smartFox.Connect(serverIP, Convert.ToInt32(serverPort));
			}
		
		}
		else if (smartFox.IsConnected()) {
			// Login
			GUI.Label(new Rect(10, 116, 100, 100), "Username: ");
			username = GUI.TextField(new Rect(100, 116, 200, 20), username, 25);

			GUI.Label(new Rect(10, 218, 100, 100), loginErrorMessage);

			if ( GUI.Button(new Rect(100, 166, 100, 24), "Login")  || (Event.current.type == EventType.keyDown && Event.current.character == '\n')) {
				smartFox.Login(zone, username, "");
			}

		} else {
			GUI.Label(new Rect(10, 150, 100, 100), "Waiting for connection");
			GUI.Label(new Rect(10, 218, 100, 100), loginErrorMessage);
		}
	}

	/************
	 * Helper methods
	 ************/

	private void UnregisterSFSSceneCallbacks() {
		// This should be called when switching scenes, so callbacks from the backend do not trigger code in this scene
		SFSEvent.onConnection -= OnConnection;
		SFSEvent.onConnectionLost -= OnConnectionLost;
		SFSEvent.onLogin -= OnLogin;
		SFSEvent.onRoomListUpdate -= OnRoomList;
		SFSEvent.onDebugMessage -= OnDebugMessage;
	}

	/************
	 * Callbacks from the SFS API
	 ************/

	void OnConnection(bool success, string error) {
		if ( success ) {
			SmartFox.Connection = smartFox;
		} else {
			loginErrorMessage = error;
		}
	}

	void OnConnectionLost() {
		loginErrorMessage = "Connection lost / no connection to server";
	}

	public void OnDebugMessage(string message) {
		Debug.Log("[SFS DEBUG] " + message);
	}

	public void OnLogin(bool success, string name, string error) {
		if ( success ) {
			// Lets wait for the room list

		} else {
			// Login failed - lets display the error message sent to us
			loginErrorMessage = error;
		}
	}

	void OnRoomList(Hashtable roomList) {
		// When room list is updated we are ready to move on to the island
		UnregisterSFSSceneCallbacks();
		Application.LoadLevel("Room_1");
	}
}