using System.Collections.Generic;
using System;
using System.Globalization;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace AyaNova.Biz
{
    public static class SqlSelectBuilder
    {

        //Build the SELECT portion of a list query based on the template, mini or full and the object key in question 
        public static string Build(string objectKey, string template, bool mini)
        {

            //parse the template
            var jtemplate = JObject.Parse(template);

            //get the fields list
            var objectFieldsList = ObjectFields.ObjectFieldsList(objectKey);

            //convert to strings array (https://stackoverflow.com/a/33836599/8939)
            string[] templateFieldList;
            if (mini)
            {
                templateFieldList = ((JArray)jtemplate["mini"]).ToObject<string[]>();
            }
            else
            {
                templateFieldList = ((JArray)jtemplate["full"]).ToObject<string[]>();
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT ");

            //Default ID column for each row (always is aliased as df)
            ObjectField def = objectFieldsList.FirstOrDefault(x => x.Key == "df");
            if (def == null)
            {
                throw new System.ArgumentNullException($"SqlSelectBuilder: objectFieldList for key \"{objectKey}\" is missing the df default field");
            }
            if (string.IsNullOrEmpty(def.SqlIdColumn))
            {
                sb.Append("id");//default when no alternate column is specified
            }
            else
            {
                sb.Append(def.SqlIdColumn);
            }

            sb.Append(" AS df");

            foreach (string ColumnName in templateFieldList)
            {
                ObjectField o = objectFieldsList.FirstOrDefault(x => x.Key == ColumnName);
#if (DEBUG)
                //Developers little helper
                if (o == null)
                {
                    throw new System.ArgumentNullException($"DEV ERROR in SqlSelectBuilder.cs: field {ColumnName} specified in template was NOT found in ObjectFields list for key \"{objectKey}\"");
                }
#endif
                if (o != null)
                {//Ignore missing fields in production

                    sb.Append(", ");
                    sb.Append(o.GetSqlColumnName());

                }
            }




            return sb.ToString();
        }



    }//eoc
}//ens
