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 SqlFilterOrderByBuilder
    {

        public static string DefaultGetManyOrderBy()
        {
            return "ORDER BY ID DESC";
        }

         public static string DefaultPickListOrderBy()
        {
            return "ORDER BY NAME ASC";
        }

        public static string DataFilterToSQLOrderBy(AyaNova.Models.DataFilter dataFilter)
        {

            if (string.IsNullOrWhiteSpace(dataFilter.Sort))
            {
                return DefaultGetManyOrderBy();
            }

            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>();
                
                sb.Append(" ");
                sb.Append(fld);
                sb.Append(" ");
                sb.Append(dir == "+" ? "ASC" : "DESC");

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

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



    }//eoc
}//ens
