using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using AyaNova.Models;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;


namespace AyaNova.PickList
{
    internal static class PickListFetcher
    {
        internal static async Task<List<NameIdActiveItem>> GetResponseAsync(IAyaPickList PickList, string autoCompleteQuery,
        string tagSpecificQuery, bool includeInactive, long preId, AyContext ct, ILogger log)
        {

            //Sort out effective Template
            string Template = null;
            //Attempt to fetch custom template              
            var t = await ct.PickListTemplate.FirstOrDefaultAsync(z => z.Id == ((long)PickList.DefaultListObjectType));
            if (t == null)
            {
                Template = PickList.DefaultTemplate;
            }
            else
            {
                Template = t.Template;
            }

            //parse the template 
            var jTemplate = JArray.Parse(Template);

            //Get the field key names in a list from the template
            List<string> TemplateColumnNames = PickList.GetFieldListFromTemplate(jTemplate);

            //BUILD THE QUERY  
            var q = PickListSqlBuilder.Build(PickList, TemplateColumnNames, autoCompleteQuery, tagSpecificQuery, includeInactive, preId);

            //RETURN OBJECTS  
            var ret = new List<NameIdActiveItem>();

            //QUERY THE DB
            using (var command = ct.Database.GetDbConnection().CreateCommand())
            {
                await ct.Database.OpenConnectionAsync();

                //GET DATA RETURN ROWS
                command.CommandText = q;
                try
                {
                    using (var dr = await command.ExecuteReaderAsync())
                    {
                        while (dr.Read())
                        {
                            //query is always in the same order:
                            //plId, plActive, plName
                            ret.Add(new NameIdActiveItem
                            {
                                Id = dr.GetInt64(0),
                                Active = dr.GetBoolean(1),
                                Name = dr.GetString(2)
                            });
                        }
                    }
                }
                catch (Npgsql.PostgresException e)
                {
                    //log out the exception and the query
                    log.LogInformation("PickList query failed unexpectedly.  Query was:");
                    log.LogInformation(q);
                    log.LogInformation(e, "DB Exception");
                    throw new System.Exception("PickListFetcher - Query failed see log");

                }
            }
            return ret;
        }
    }//eoc
}//eons