using System;
using System.Collections.Generic;

namespace AS400API.Configuration;

public sealed class OdbcOptions
{
    public string? System { get; set; }
    public string? DefaultLibraries { get; set; }
    public string? User { get; set; }
    public string? Password { get; set; }
    /// <summary>
    /// 0 = SQL naming (*SYS = library/file); 1 = System naming (*SYS). Keep 1 by default.
    /// </summary>
    public string? Naming { get; set; }
    public string? Translate { get; set; } = "1";
    public string? ClientLocale { get; set; } = "en_US";
    public bool Pooling { get; set; } = true;

    public string ToConnectionString()
    {
        // Driver name must match installed name in odbcinst.ini
        var driverName = Environment.GetEnvironmentVariable("AS400_DRIVER_NAME") ?? "IBM i Access ODBC Driver";
        var parts = new List<string>
        {
            $"Driver={{{driverName}}}",
            $"System={System}"
        };
        if (!string.IsNullOrWhiteSpace(DefaultLibraries)) parts.Add($"DefaultLibraries={DefaultLibraries}");
        if (!string.IsNullOrWhiteSpace(User)) parts.Add($"Uid={User}");
        if (!string.IsNullOrWhiteSpace(Password)) parts.Add($"Pwd={Password}");
        if (!string.IsNullOrWhiteSpace(Naming)) parts.Add($"Naming={Naming}");
        if (!string.IsNullOrWhiteSpace(Translate)) parts.Add($"TRANSLATE={Translate}");
        if (!string.IsNullOrWhiteSpace(ClientLocale)) parts.Add($"Client_Locale={ClientLocale}");
        if (Pooling) parts.Add("Pooling=true");
        return string.Join(";", parts);
    }
}
