using Org.BouncyCastle.Asn1.X509;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;

namespace TSManagementApp.Utils
{
    public static class CertificateUtils
    {
        public static string FindCertCommonName(X509Certificate2 cert)
        {
            X509Name subject = X509Name.GetInstance(cert.SubjectName.RawData);
            var oidList = subject.GetOidList();
            var valueList = subject.GetValueList();
            ICollection<Tuple<string, string>> list = new List<Tuple<string, string>>();
            for (int i = 0; i < oidList.Count; i++)
                list.Add(ConvertOid(oidList[i].ToString(), valueList[i].ToString()));
            return list?.FirstOrDefault(t => t.Item1 == "CN")?.Item2;
        }

        private static Tuple<string, string> ConvertOid(string oid, string value)
        {
            switch (oid)
            {
                case "2.5.4.3":
                    return new Tuple<string, string>("CN", value);
                case "2.5.4.4":
                    return new Tuple<string, string>("SN", value);
                case "2.5.4.5":
                    return new Tuple<string, string>("serialNumber", value);
                case "2.5.4.6":
                    return new Tuple<string, string>("C", value);
                case "2.5.4.7":
                    return new Tuple<string, string>("L", value);
                case "2.5.4.8":
                    return new Tuple<string, string>("ST", value);
                case "2.5.4.9":
                    return new Tuple<string, string>("streetAddress", value);
                case "2.5.4.10":
                    return new Tuple<string, string>("O", value);
                case "2.5.4.11":
                    return new Tuple<string, string>("OU", value);
                case "2.5.4.12":
                    return new Tuple<string, string>("T", value);
                case "2.5.4.17":
                    return new Tuple<string, string>("postalCode", value);
                case "2.5.4.42":
                    return new Tuple<string, string>("GN", value);
                case "2.5.4.43":
                    return new Tuple<string, string>("initials", value);
                case "2.5.4.44":
                    return new Tuple<string, string>("generation", value);
                case "2.5.4.97":
                    return new Tuple<string, string>("organizationIdentifier", value);
                default:
                    return new Tuple<string, string>("", value);
            }
        }

    }
}
