using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Valg.EVA.Skanning.Contracts;
using Valg.EVA.Skanning.Tools;

namespace Valg.EVA.Skanning.Configuration
{
    public class EncryptedDatabaseConfiguration : IDatabaseConfiguration
    {
        public string ConnectionString { get; set; }
        public string DatabaseServerName { get; set; }
        public string DatabaseVersion { get; set; }
        public bool OverrideTimeOut { get; set; }
        public int TransactionTimeOut { get; set; }
        public int CommandTimeOut { get; set; }
        private readonly DataProtectionApi dataProtectionApi = new DataProtectionApi();

        private readonly IApplicationConfigurationReader applicationConfigurationReader = null;
        public EncryptedDatabaseConfiguration(IApplicationConfigurationReader applicationConfigurationReader)
        {
            this.applicationConfigurationReader = applicationConfigurationReader;

            ConnectionString = GetUnencryptedConnectionString();

            var internalConnectionStringBuilder = new SqlConnectionStringBuilder(ConnectionString);
            DatabaseServerName = internalConnectionStringBuilder.DataSource;

            DatabaseVersion = applicationConfigurationReader.GetAppSetting("DatabaseVersion");
            OverrideTimeOut = Convert.ToBoolean(applicationConfigurationReader.GetAppSetting("OverrideTimeOut"));
            CommandTimeOut = Convert.ToInt32(applicationConfigurationReader.GetAppSetting("CommandTimeOut"));
            TransactionTimeOut = Convert.ToInt32(applicationConfigurationReader.GetAppSetting("TransactionTimeOut"));
        }

        private string GetUnencryptedConnectionString()
        {
            var connectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder(applicationConfigurationReader.GetConnectionString());

            if (connectionStringBuilder.IntegratedSecurity || !IsValidBase64String(connectionStringBuilder.Password))
            {
                return connectionStringBuilder.ConnectionString;
            }
            else
            {
                connectionStringBuilder.Password = dataProtectionApi.Decrypt(connectionStringBuilder.Password);
                return connectionStringBuilder.ConnectionString;
            }
        }

        public static bool IsValidBase64String(string input)
        {
            try
            {
                Convert.FromBase64String(input);
                return true;
            }
            catch (FormatException)
            {
                return false;
            }
        }
    }
}

