using System.Windows.Forms;
using ComponentPro.Security.Certificates;

namespace Pop3Client.Security
{
    public partial class CertProvider : Form
    {
        private X509Certificate[] _certs;
        private X509Certificate _selectedCertificate;

        public X509Certificate SelectedCertificate
        {
            get
            {
                return _selectedCertificate;
            }
        }
		
        public CertProvider()
        {
            InitializeComponent();
        }

        public void LoadData(X509Certificate[] certs)
        {
            _certs = certs;

            for (int i = 0; i < certs.Length; i++)
            {
                cbCertList.Items.Add(certs[i].SubjectName);
            }

            if (certs.Length > 0)
            {
                cbCertList.SelectedIndex = 0;

                X509Certificate cert = certs[0];

                lblOrganizationText.Text = cert.Issuer.OrganizationName;
                lblUnitText.Text = cert.Issuer.UnitName;
                lblLocationText.Text = string.Format("Country Code: {0}, State: {1}, City: {2}", cert.Issuer.CountryCode, cert.Issuer.State, cert.Issuer.City);
                lblCommonNameText.Text = cert.Issuer.CommonName;

                lblOrganizationSubText.Text = cert.Subject.OrganizationName;
                lblUnitSubText.Text = cert.Subject.UnitName;
                lblLocationSubText.Text = string.Format("Country Code: {0}, State: {1}, City: {2}", cert.Subject.CountryCode, cert.Subject.State, cert.Subject.City);
                lblCommonNameSubText.Text = cert.Subject.CommonName;

                lblFromText.Text = cert.EffectiveDate.ToString();
                lblToText.Text = cert.ExpiryDate.ToString();
            }
        }

        private void cbCertList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (cbCertList.SelectedIndex != -1)
            {
                int selIndex = cbCertList.SelectedIndex;
                X509Certificate c = _certs[selIndex];

                lblOrganizationText.Text = c.IssuerName;
                lblOrganizationSubText.Text = c.SubjectName;

                lblFromText.Text = c.EffectiveDate.ToString();
                lblToText.Text = c.ExpiryDate.ToString();
                //lblSubject.Text = _certs[selIndex].SubjectName;
                //lblIssuer.Text = _certs[selIndex].IssuerName;
                //lblValidFrom.Text = _certs[selIndex].EffectiveDate.ToString();
                //lblValidTo.Text = _certs[selIndex].ExpiryDate.ToString();
            }
        }

        private void btnOk_Click(object sender, System.EventArgs e)
        {
            if (cbCertList.SelectedIndex != -1)
                _selectedCertificate = _certs[cbCertList.SelectedIndex];
            else
                _selectedCertificate = null;

            this.Close();
        }        
    }
}