using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32;

namespace Valg.EVA.Skanning.Services.InstallClientCertificate
{
    public class InstallClientCertificateService : IInstallClientCertificateService
    {
        public ClientCertificateInstallationResult InstallClientCertificate(string pathToClientCertificate, string password)
        {
            var result = new ClientCertificateInstallationResult();
            try
            {
                var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadWrite);

                
                
                store.Add(new X509Certificate2(File.ReadAllBytes(pathToClientCertificate), password,
                    X509KeyStorageFlags.MachineKeySet |
                    X509KeyStorageFlags.PersistKeySet | 
                    X509KeyStorageFlags.PersistKeySet | 
                    X509KeyStorageFlags.Exportable));

                store.Close();
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message.TrimEnd();
                result.Success = false;
            }
            return result;
        }

        public virtual string SelectClientCertificate()
        {
            var selectedClientCertificatePath = string.Empty;
            var openFileDialog = new OpenFileDialog { DefaultExt = "*.p12", Filter = "PKCS #12 | *.p12" };
            var hasValue = openFileDialog.ShowDialog();
            if (IsTrue(hasValue))
            {
                selectedClientCertificatePath = openFileDialog.FileName;
            }
            return selectedClientCertificatePath;
        }

        private static bool IsTrue(bool? hasValue)
        {
            return hasValue.HasValue && hasValue.Value;
        }
    }
}
