using System.Text;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace AyaNova.DataList
{
    public static class DataListSqlFilterOrderByBuilder
    {

        // public static string DefaultGetManyOrderBy => "ORDER BY ID DESC";

        // public static string DefaultPickListOrderBy => "ORDER BY NAME ASC";

        public static string DataFilterToSQLOrderBy(List<AyaDataListFieldDefinition> objectFieldsList, AyaNova.Models.DataListFilter dataFilter)
        {

            if (string.IsNullOrWhiteSpace(dataFilter.Sort))
            {
                //sort by default field descending which should in theory always be the id column of the main object in the list
                //which should return the results to user with most recent records at the top if no sort order was specified
                if(objectFieldsList[0].FieldKey=="df"){
                    return $"ORDER BY {objectFieldsList[0].SqlIdColumnName} DESC";
                }else{
                    //no default column so no idea how to sort
                    return string.Empty;
                }               
            }

            StringBuilder sb = new StringBuilder();

            //iterate the datafilter and concatenate a sql query from it
            var SortArray = JArray.Parse(dataFilter.Sort);
            for (int i = 0; i < SortArray.Count; i++)
            {

                var SortItem = SortArray[i];
                var fld = SortItem["fld"].Value<string>();
                var dir = SortItem["dir"].Value<string>();
                //Get the correct sql column name
                AyaDataListFieldDefinition DataListField = objectFieldsList.FirstOrDefault(x => x.FieldKey == fld);
#if (DEBUG)
                //Developers little helper
                if (DataListField == null)
                {
                    throw new System.ArgumentNullException($"DEV ERROR in DataListSqlFilterOrderByBuilder.cs: field {fld} specified in template was NOT found in ObjectFields list");
                }
#endif
                var SQLValueColumnName = DataListField.GetSqlValueColumnName();

                sb.Append(" ");
                sb.Append(SQLValueColumnName);
                sb.Append(" ");
                sb.Append(dir == "+" ? "ASC" : "DESC");

                if (i < SortArray.Count - 1)
                {
                    sb.Append(",");
                }
            }

            return "ORDER BY" + sb.ToString();
        }



    }//eoc
}//ens
