using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pluto.Api;
using System.Net;
using Pluto.Registration;

namespace AutoUpdater
{
    internal static class RegistrationWrapper
    {
        // Allow the Registration wrapper to let the Service enter into a different 'disconnected' state
        internal static int HasConnectivityErrorCountInARow = 0;
        internal static int HasConnectivityErrorCountMaxBeforeStateChange = 10;
        internal static string RegistrationHOST = "";
        internal static uint RegistrationPORT = 0;

        private const string DEFAULT_REGISTRATION_HOST_N_PORT_URL = "http://ppsmobile.mckesson.com/mobile1/REGURL.htm";
        private const string DEFAULT_REGISTRATION_HOST_URL = "ppsmobile.mckesson.com";
        private const int DEFAULT_REGISTRATION_CHANNEL_PORT = 443;

        #region Connectivity

        /// <summary>
        /// Check to make sure we can communicate with the Registration Service.
        /// Check the Server's ip & port for connectivity as well as that this
        /// computer has connectivity. 
        /// This way we won't throw any connectivity errors, which is good.
        /// </summary>        
        /// <returns>true, if successfully can connect, false otherwise</returns>
        private static bool HasConnectivity()
        {
            try
            {
                bool bCanConnect = false;
                bool bUseConfiguration = true;

                // Try the overwritten Registration Host and Port first, if exists
                if (RegistrationHOST != "" && RegistrationPORT > 0)
                {
                    bCanConnect = Yaulw.Net.IPHostHelper.HasConnectivity(RegistrationHOST, RegistrationPORT, 0);
                    if (bCanConnect)
                        bUseConfiguration = false;
                }

                // Else, fall-back on the configuration, if we couldn't connect
                if (!bCanConnect)
                {
                    bCanConnect = Yaulw.Net.IPHostHelper.HasConnectivity(DEFAULT_REGISTRATION_HOST_URL, (uint)DEFAULT_REGISTRATION_CHANNEL_PORT, 0);
                    if (bCanConnect)
                        bUseConfiguration = true;
                }

                if (bCanConnect)
                {                    
                    if (bUseConfiguration)
                    {
                        IPAddress ip = Yaulw.Net.IPHostHelper.GetIpForHost(DEFAULT_REGISTRATION_HOST_URL);
                        RegistrationAPI.API.SetNetworkSettings(ip.ToString(), (uint)DEFAULT_REGISTRATION_CHANNEL_PORT);
                    }
                    else
                    {
                        IPAddress ip = Yaulw.Net.IPHostHelper.GetIpForHost(RegistrationHOST);
                        RegistrationAPI.API.SetNetworkSettings(ip.ToString(), RegistrationPORT);
                    }
                    HasConnectivityErrorCountInARow = 0;
                }
                else
                {
                    // Try to retrieve the latest Host and Port Setting online
                    try
                    {
                        string HostNPortSetOnline = Yaulw.Net.WCHelper.ScreenScrapeFromURL(DEFAULT_REGISTRATION_HOST_N_PORT_URL);
                        if (!String.IsNullOrEmpty(HostNPortSetOnline))
                        {
                            RegistrationHOST = HostNPortSetOnline.Split(';')[0];
                            RegistrationPORT = uint.Parse(HostNPortSetOnline.Split(';')[1]);
                        }
                    }
                    catch (Exception) 
                    { 
                        /* ignore */
                    }

                    // Try to connection one more time
                    if (RegistrationHOST != "" && RegistrationPORT > 0)
                        bCanConnect = Yaulw.Net.IPHostHelper.HasConnectivity(RegistrationHOST, RegistrationPORT, 0);

                    // if we can connect, we are Golden
                    if (bCanConnect)
                    {                        
                        IPAddress ip = Yaulw.Net.IPHostHelper.GetIpForHost(RegistrationHOST);
                        RegistrationAPI.API.SetNetworkSettings(ip.ToString(), RegistrationPORT);
                        HasConnectivityErrorCountInARow = 0;
                    }
                    else
                    {
                        // Connectivity Errors too plentiful - Change the state of the service to reflect that
                        if (HasConnectivityErrorCountInARow >= HasConnectivityErrorCountMaxBeforeStateChange)
                        {                            
                            //PlutoService.state = HostGUIDstate.no_connectivity;
                        }
                        else
                        {                         
                            HasConnectivityErrorCountInARow++;
                        }
                    }
                }
                return bCanConnect;                
            }
            catch (Exception)
            {                
            }
            return false;
        }

        #endregion

        #region AutoUpdate / Client / Server Calls

        public static Client[] GetClients()
        {
            try
            {
                if (HasConnectivity())
                {
                    Client[] clients = RegistrationAPI.API.GetExternalClients();
                    return clients;
                }
            }
            catch
            {
                /* ignore */
            }
            return null;
        }

        #endregion
    }
}
