using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
namespace Sockeye.Biz
{

    //Turn a type and ID into a displayable name   
    //Used by search and eventlog processor
    internal static class BizObjectNameFetcherDirect
    {
        internal static string Name(SockType sockType, long id, long translationid, System.Data.Common.DbCommand cmd)
        {
            try
            {
                string ret;

                cmd.CommandText = $"select PUBLIC.AYGETNAME({id}, {(int)sockType}, {translationid}) as m";
                using (var dr = cmd.ExecuteReader())
                {
                    if (dr.Read())
                    {
                        if (dr.IsDBNull(0))
                            ret = $"?? type:{sockType},id:{id}";
                        else
                            ret = dr.GetString(0);
                    }
                    else
                    {
                        ret = "-";
                    }
                    //return dr.Read() ? dr.GetString(0) : "-";
                }
                return ret;

            }
            catch
            {
                ((ILogger)Sockeye.Util.ApplicationLogging.CreateLogger("BizObjectNameFetcherDirect")).LogError($"### Error fetching for type {sockType}");
                throw;
            }
        }

        //warning: use the above in a loop, not this one
        internal static string Name(SockType sockType, long id, long translationId, Sockeye.Models.AyContext ct)
        {
            using (var command = ct.Database.GetDbConnection().CreateCommand())
            {
                ct.Database.OpenConnection();
                return Name(sockType, id,translationId, command);
            }
        }

    }//eoc
}//eons

