using ComponentPro.Net;
using ComponentPro.Security.Certificates;

namespace Pop3Client.Security
{
    class CustomCertProvider :
       ICertificateChainProvider
    {
        /// <summary>
        /// Validates a certificate and returns a chain object.
        /// </summary>
        /// <param name="info">The request info.</param>
        /// <returns>CertificateChain chain object.</returns>
        public X509CertificateChain GetChain(CertificateChainProviderRequestInfo info)
        {
            CertificateStore my = new CertificateStore("MY");
            X509Certificate[] certs;

            if (info.GetIssuers().Length > 0)
                certs = my.GetCertificates
                    (
                    info.GetIssuers(),
                    CertificateSearchType.TimeValid |
                    CertificateSearchType.HasPrivateKey |
                    CertificateSearchType.ClientAuthentication
                    );
            else
                certs = my.GetCertificates
                    (
                    CertificateSearchType.TimeValid |
                    CertificateSearchType.HasPrivateKey |
                    CertificateSearchType.ClientAuthentication
                    );

            if (certs.Length == 0)
                return null;

            CertProvider rhForm = new CertProvider();
            rhForm.LoadData(certs);

            if (rhForm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (rhForm.SelectedCertificate != null)
                    return X509CertificateChain.Create(rhForm.SelectedCertificate);
            }

            return null;
        }
    }
}