using System;
using System.Collections.Generic;
//using System.Collections;
using System.Text;
using System.Data;
using SEILoader.SEI;
using SEILoader.SIMPB;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Runtime.CompilerServices;
using System.Threading;
using log4net;

namespace SEILoader
{
    class TokenManager
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        
        private static void loadTokens()
        {
            log.Debug("inizio loadTokens()");
            string codiceApplicazione = Properties.Settings.Default.codiceApplicazione;
            string reteBF = Properties.Settings.Default.codiceBF;
            string reteSPI = Properties.Settings.Default.codiceSPI;
            string useridSIMPB = Properties.Settings.Default.useridSIMPB;
            string pwdSIMPB = Properties.Settings.Default.pwdSIMPB;

            Token tokenWS = new Token();
            tokenWS.PreAuthenticate = true;
            System.Net.NetworkCredential cred = new System.Net.NetworkCredential(useridSIMPB, pwdSIMPB);
            tokenWS.Credentials = cred;
            
            //System.Net.SecurityProtocolType.Ssl3;
            System.Net.ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(VerifyServerCertificate);

            InfoClient[] infoC = new InfoClient[2];
            infoC[0] = new InfoClient();
            infoC[0].codiceApplicazione = codiceApplicazione;
            infoC[0].versioneDatabaseSIMPB = 0;
            infoC[0].codiceRete = reteBF;
            infoC[1] = new InfoClient();
            infoC[1].codiceApplicazione = codiceApplicazione;
            infoC[1].versioneDatabaseSIMPB = 0;
            infoC[1].codiceRete = reteSPI;
            TokenRes tok = tokenWS.getToken(infoC);
            
            tokens = new SortedDictionary<string, int>();
            if (tok.allToken.Length == 2)
            {
                if (tok.allToken[0].codiceRete == reteBF)
                {
                    tokens.Add(reteBF, tok.allToken[0].versioneDataBase);
                    tokens.Add(reteSPI, tok.allToken[1].versioneDataBase);
                }
                else
                {
                    tokens.Add(reteSPI, tok.allToken[0].versioneDataBase);
                    tokens.Add(reteBF, tok.allToken[1].versioneDataBase);
                }
            }
            log.Info("loadTokens() BF=" + tokens[reteBF] + " SPI=" + tokens[reteSPI]);

        }
        private static bool VerifyServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None) return true;


            foreach (X509ChainStatus s in chain.ChainStatus)
            {
                // allows expired certificates
                if (string.Equals(s.Status.ToString(), "NotTimeValid",
                    StringComparison.OrdinalIgnoreCase))
                    return true;
            }

            return true;
        }

        private static SortedDictionary<String, int> tokens = null;

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static int getToken(string rete)
        {
            if (tokens == null)
            {
                loadTokens();
            }
            int token = 0;
            tokens.TryGetValue(rete, out token);
            return token;
        }

        public static void resetTokens(){
            tokens = null;
        }

    }
}