using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Valg.EVA.Skanning.Diagnostics;

namespace Valg.EVA.Skanning.Signing
{
    public class SignatureCryptographicServiceProvider : ISignatureCryptographicServiceProvider
    {
        private readonly ICertificates certificates;

        public SignatureCryptographicServiceProvider(ICertificates certificates)
        {
            this.certificates = certificates;
        }

        public SignatureCryptographicServiceProviderResult Sign(byte[] data)
        {
            var result = new SignatureCryptographicServiceProviderResult();
            var certificate = certificates.FindSertificate();

            if (certificate != null)
            {
                try
                {
                    result.SignedData = SignData(data, certificate);
                    result.SigningCertificate = certificate;
                    result.IsSigningSuccessful = true;
                }
                catch (Exception ex)
                {
                    result.IsSigningSuccessful = false;
                    EvaSkanningEventSource.Log.SigningOfDataFailed(ex.ToString());
                }
            }
            else
            {
                result.IsSigningCertificateMissing = true;
                result.IsSigningSuccessful = false;
            }

            return result;
        }

        public bool IsServiceReadyToSign()
        {
            return certificates.FindSertificate() != null;
        }

        

	    private static byte[] SignData(byte[] data, X509Certificate2 certificate)
	    {
		    using (var rsa = certificate.GetRSAPrivateKey())
		    {		        
			    return rsa.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
		    }
	    }

    }
}

