using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;


namespace PkcsApp
{
    class Certificate
    {
        public string tokenLabel { get; private set; }
        public bool sign { get; private set; }
        public bool nonRepudiation { get; private set; }
        public byte[] ID { get; private set; } //link to private key
        public string label { get; private set; }


        public X509Certificate2 cert { get; private set; }
        


        public Certificate(byte[] pem, string tokenLabel, string label = null, byte[] ID = null)
        {
            this.tokenLabel = tokenLabel;
            this.label = label;
            this.ID = ID;
            cert = new X509Certificate2(pem);

            foreach( var ext in cert.Extensions.OfType<X509KeyUsageExtension>())
            {
                if((ext.KeyUsages & X509KeyUsageFlags.DigitalSignature) == X509KeyUsageFlags.DigitalSignature)
                {
                    sign = true;
                }

                if ((ext.KeyUsages & X509KeyUsageFlags.NonRepudiation) == X509KeyUsageFlags.NonRepudiation)
                {
                    nonRepudiation = true;
                }
            }


        }

        public bool verifyHash(byte[] signature, byte[] hashedData, string hashAlgorithm)
        {
            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
            return csp.VerifyHash(hashedData, CryptoConfig.MapNameToOID(hashAlgorithm), signature);
        }

        public bool verifyData(byte[] signature, byte[] data, string hashAlgorithm)
        {
            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
            return csp.VerifyData(data, CryptoConfig.MapNameToOID(hashAlgorithm), signature);
        }


        public bool verifyThisCertificate(List<Certificate> certs)
        {
            throw new NotImplementedException();
        }
        public string getPem()
        {
            StringBuilder str = new StringBuilder();
            str.AppendLine("-----BEGIN CERTIFICATE-----");
            str.AppendLine(Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
            str.AppendLine("-----END CERTIFICATE-----");

            return str.ToString();
        }

    }
}
