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

namespace AyaNova.DataList
{
    public static class DataListSqlFilterOrderByBuilder
    {


        public static string DataFilterToSQLOrderBy(List<AyaDataListFieldDefinition> objectFieldsList, JArray listViewArray)
        {

            StringBuilder sb = new StringBuilder();

            //iterate the datafilter and concatenate a sql query from it
            //  [{key:"COLUMN UNIQUE KEY ID",sort:"-" or "+",filter:{any:true/false,items:[{FILTER OBJECT SEE BELOW}]} }, {key:"second column unique key"},{...etc...}]
            bool SortItemAdded = false;
            for (int i = 0; i < listViewArray.Count; i++)
            {
                var cm = listViewArray[i];
                //skip it if sort is not defined
                if (cm["sort"] == null)
                {
                    continue;
                }
                var fld = cm["fld"].Value<string>();
                var dir = cm["sort"].Value<string>();
                //Get the correct sql column name
                AyaDataListFieldDefinition DataListField = objectFieldsList.FirstOrDefault(z => z.FieldKey == fld);
                //No sorting on custom fields!
                if (DataListField.IsCustomField)
                {
                    continue;
                }
#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();

                if (SortItemAdded)
                    sb.Append(", ");
                else
                    sb.Append(" ");
                sb.Append(SQLValueColumnName);
                sb.Append(" ");
                sb.Append(dir == "+" ? "ASC" : "DESC");

                SortItemAdded = true;
            }

            if (sb.Length == 0)
            {
                //no sort specified so default it
                AyaDataListFieldDefinition rid = objectFieldsList.FirstOrDefault(z => z.IsRowId == true);
                if (rid != null)
                {
                    return $"ORDER BY {rid.SqlIdColumnName} DESC";
                }
                else
                {
                    //no default column so no idea how to sort
                    return string.Empty;
                }
            }
            else
            {
                return "ORDER BY" + sb.ToString();
            }
        }



    }//eoc
}//ens
