Imports System.Windows.Forms
Imports ComponentPro.Security.Certificates

Namespace Pop3Client.Security
	Partial Public Class CertProvider
		Inherits Form
		Private _certs() As X509Certificate
		Private _selectedCertificate As X509Certificate

		Public ReadOnly Property SelectedCertificate() As X509Certificate
			Get
				Return _selectedCertificate
			End Get
		End Property

		Public Sub New()
			InitializeComponent()
		End Sub

		Public Sub LoadData(ByVal certs() As X509Certificate)
			_certs = certs

			For i As Integer = 0 To certs.Length - 1
				cbCertList.Items.Add(certs(i).SubjectName)
			Next i

			If certs.Length > 0 Then
				cbCertList.SelectedIndex = 0

				Dim cert As X509Certificate = 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()
			End If
		End Sub

		Private Sub cbCertList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbCertList.SelectedIndexChanged
			If cbCertList.SelectedIndex <> -1 Then
				Dim selIndex As Integer = cbCertList.SelectedIndex
				Dim c As X509Certificate = _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();
			End If
		End Sub

		Private Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOk.Click
			If cbCertList.SelectedIndex <> -1 Then
				_selectedCertificate = _certs(cbCertList.SelectedIndex)
			Else
				_selectedCertificate = Nothing
			End If

			Me.Close()
		End Sub
	End Class
End Namespace