using e_suite.API.Common.extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MySqlConnector;

namespace e_suite.Service.SigmaImporter.Repository;

public class MySqlRepositoryBase : IDisposable
{
    protected readonly ILogger Logger;
    protected readonly string ConfigSection;
    protected readonly IConfiguration Configuration;

    private MySqlConnection? _connection = null;

    protected MySqlConnection Connection
    {
        get
        {
            if (_connection == null)
            {
                var connectionString = BuildConnectionString(Configuration, ConfigSection);
                _connection = new MySqlConnection(connectionString);
                _connection.Open();
            }
            return _connection;
        }
    }

    public string BuildConnectionString(IConfiguration configuration, string configSection)
    {
        var server = configuration.GetConfigValue($"{configSection}_SERVER", $"{configSection}:Server", "");
        var database = configuration.GetConfigValue($"{configSection}_DATABASE", $"{configSection}:Database", "");
        var userId = configuration.GetConfigValue($"{configSection}_USERID", $"{configSection}:UserID", "");
        var password = configuration.GetConfigValue($"{configSection}_PASSWORD", $"{configSection}:Password", "");

        //var sb = new StringBuilder();
        //sb.Append("Compiling ConnectionString for ");
        //sb.AppendLine(configSection);
        //sb.Append("Server: ");
        //sb.AppendLine(server);
        //sb.Append("Database: ");
        //sb.AppendLine(database);
        //sb.Append("UserId: ");
        //sb.AppendLine(userId);
        //sb.Append("Password length: ");
        //sb.AppendLine(password!.Length.ToString());

        //_logger.LogInformation(sb.ToString());

        var builder = new MySqlConnectionStringBuilder
        {
            Server = server,
            Database = database,
            UserID = userId,
            Password = password
        };

        return builder.ToString();
    }
    
    protected MySqlRepositoryBase(IConfiguration configuration, ILogger logger, string configSection)
    {
        Configuration = configuration;
        ConfigSection = configSection;
        Logger = logger;
    }



    public void Dispose()
    {
        GC.SuppressFinalize(this);
        Close();
    }

    protected void Close()
    {
        if (_connection != null)
        {
            Connection.Close();
            _connection = null;
        }
            
    }
}