using System.Data;
using Microsoft.Data.SqlClient;

namespace IWS5.Server.DataAccess;
internal static class Repository
{
    internal static string GetRecordValue(SqlConnection sqlConnection, string sqlStatement, Dictionary<string, object> parameters = null)
    {
        //This is to obtain a single value
        string returnValue = "";

        try
        {
            var sqlCommand = new SqlCommand(sqlStatement, sqlConnection);
            if (parameters != null && parameters.Count > 0)
            {
                foreach (var parameter in parameters)
                {
                    sqlCommand.Parameters.AddWithValue(parameter.Key, parameter.Value);
                }
            }

            SqlDataAdapter dap = new SqlDataAdapter(sqlCommand);
            System.Data.DataSet ds = new System.Data.DataSet();
            dap.Fill(ds);

            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow tr in ds.Tables[0].Rows)
                {
                    returnValue = tr[0].ToString();
                }
            }

            return returnValue;
        }
        catch (Exception)
        {
            return "";
        }
    }

    internal static int GetQueueId(SqlConnection sqlConnection, int eventId)
    {
        var sqlQuery = "SELECT [Id] FROM [ATQueue] WHERE [EventId] = @eventId";
        string sqlValue = GetRecordValue(sqlConnection, sqlQuery, new Dictionary<string, object>
        {
            { "@eventId", eventId }
        });

        if (string.IsNullOrEmpty(sqlValue))
        {
            return 0;
        }

        return Convert.ToInt32(sqlValue);
    }

    internal static int GetQueueEventId(SqlConnection sqlConnection, int queueId)
    {
        var sqlQuery = "SELECT [EventId] FROM [ATQueue] WHERE [Id] = @queueId";
        string sqlValue = GetRecordValue(sqlConnection, sqlQuery, new Dictionary<string, object>
        {
            {"@queueId", queueId}
        });

        if (string.IsNullOrEmpty(sqlValue))
        {
            return 0;
        }
        else
        {
            return Convert.ToInt32(sqlValue);
        }
    }
}

