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

namespace Sockeye.DataList
{
    public static class DataListSqlFilterOrderByBuilder
    {
        public static string DataFilterToSQLOrderBy(List<DataListFieldDefinition> objectFieldsList, Models.DataListProcessingBase listOptions)
        {
            StringBuilder sb = new StringBuilder();
            bool SortItemAdded = false;
            foreach (KeyValuePair<string, string> kvSort in listOptions.SortBy)
            {
                //Get the correct sql column name
                DataListFieldDefinition DataListField = objectFieldsList.FirstOrDefault(z => z.FieldKey == kvSort.Key);
                //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 {kvSort.Key} 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(kvSort.Value == "+" ? "ASC" : "DESC");
                SortItemAdded = true;
            }

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

    }//eoc
}//ens
