//--------------------------------------
//               PowerUI
//
//        For documentation or 
//    if you have any issues, visit
//        powerUI.kulestar.com
//
//    Copyright  2013 Kulestar Ltd
//          www.kulestar.com
//--------------------------------------

using System;
using System.Net;
using System.Net.Sockets;


namespace PowerUI{

	/// <summary>
	/// Handles remote DOM debugging. It calls out to a known address, which may be a facilitator.
	/// Once connected and authenticated, all DOM events are sent to the debugger.
	/// </summary>

	public static class RemoteDebug{
		
		/// <summary>True if the remote debugger is active or not.</summary>
		public static bool Active;
		/// <summary>True if the remote debugger started up.</summary>
		public static bool Started;
		/// <summary>The authentication key to use to allow the debugger access.</summary>
		public static string AuthenticationKey;
		/// <summary>Location of the facilitator or the debugger. IP or DNS name.</summary>
		public static string DebugAddress="uidebug.kulestar.com";
		
		
		/// <summary>Activates and starts the debugger at runtime.</summary>
		public static void Activate(){
			Active=true;
			Start();
		}
		
		/// <summary>Starts remote debugging, but only if it is Active.</summary>
		public static void Start(){
			if(!Active){
				if(Started){
					Stop();
				}
				return;
			}
			if(string.IsNullOrEmpty(DebugAddress)){
				Dom.Log.Add("No PowerUI debugger address defined. Please check the PowerUI settings.");
				return;
			}
			Started=true;
			
			IPAddress ip=GetIP(DebugAddress);
			if(ip==null){
				Dom.Log.Add("Unable to locate PowerUI debugger. '"+DebugAddress+"' could not be resolved (internet may be down).");
			}
			
			// Attempt a connection.
		}
		
		/// <summary>Stops any active remote debugging.</summary>
		public static void Stop(){
			if(!Started){
				return;
			}
			Started=false;
		}
		
		/// <summary>Attempts to parse the given address as an IP.</summary>
		private static IPAddress GetIP(string address){
		
			IPAddress ip;
			
			if(!IPAddress.TryParse(address,out ip)){
				// DNS lookup.
				try{
					IPAddress[] addresses=Dns.GetHostAddresses(address);
					if(addresses==null || addresses.Length==0){
						return null;
					}
					ip=addresses[new System.Random().Next(0,addresses.Length)];
				}catch{}
			}
			
			return ip;
		}
		
	}

}
