using System.Linq;
using Microsoft.EntityFrameworkCore;
using AyaNova.Api.ControllerHelpers;
using AyaNova.Models;
using System.Collections.Generic;


namespace AyaNova.Biz
{
    internal static class PickListFetcher
    {

        internal static PickListResult GetPickList(AyContext ct, long userId, ListOptions pagingOptions, List<ObjectField> objectFields, string tableName)
        {

            List<NameIdItem> listItems = new List<NameIdItem>();
            int recordCount = 0;

            using (var cm = ct.Database.GetDbConnection().CreateCommand())
            {

                ct.Database.OpenConnection();

                //BUILD THE QUERY
                //base query
                string qItemBase = string.Empty;
                string qCountBase = string.Empty;
                string qCriteria = string.Empty;
                string qSort = string.Empty;
               // string q = string.Empty;

                qItemBase = $"SELECT id, name FROM {tableName} ";
                qCountBase = $"SELECT COUNT(*) FROM {tableName} ";


                //GET THE FILTER / SORT
                if (pagingOptions.DataFilterId > 0)
                {
                    var TheFilter = ct.DataFilter.FirstOrDefault(x => x.Id == pagingOptions.DataFilterId);

                    //BUILD WHERE AND APPEND IT
                    //qCriteria = FilterSqlCriteriaBuilder.DataFilterToSQLCriteria(TheFilter, WidgetBiz.FilterOptions(), userId);
                    qCriteria = SqlFilterCriteriaBuilder.DataFilterToSQLCriteria(TheFilter, objectFields, userId);

                    //BUILD ORDER BY AND APPEND IT
                    qSort = SqlFilterOrderByBuilder.DataFilterToSQLOrderBy(TheFilter);
                }
                else
                {
                    //GET DEFAULT ORDER BY
                    qSort = SqlFilterOrderByBuilder.DefaultPickListOrderBy();
                }

                //ITEMS
                //add the limit and offset values:               

                cm.CommandText = qItemBase + qCriteria + " " + qSort + $" LIMIT {pagingOptions.Limit} OFFSET {pagingOptions.Offset}";
                using (var dr = cm.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        listItems.Add(new NameIdItem() { Id = dr.GetInt64(0), Name = dr.GetString(1) });
                    }
                }

                //TOTAL RECORD COUNT
                cm.CommandText = qCountBase + qCriteria;
                using (var dr = cm.ExecuteReader())
                {
                    dr.Read();
                    recordCount = dr.GetInt32(0);
                }
            }

            PickListResult ret = new PickListResult();
            ret.Items = listItems.ToArray();
            ret.TotalRecordCount = recordCount;

            return ret;

        }


        // //Returns existance status of object type and id specified in database
        // internal static string Name(AyaType aytype, long id, System.Data.Common.DbCommand cmd)
        // {
        //     string TABLE = string.Empty;
        //     string COLUMN = "name";
        //     switch (aytype)
        //     {
        //         case AyaType.User:
        //             TABLE = "auser";
        //             break;
        //         case AyaType.Widget:
        //             TABLE = "awidget";
        //             break;

        //         case AyaType.FileAttachment:
        //             TABLE = "afileattachment";
        //             COLUMN = "displayfilename";
        //             break;
        //         case AyaType.DataFilter:
        //             TABLE = "adatafilter";
        //             break;
        //         default:
        //             throw new System.NotSupportedException($"AyaNova.BLL.BizObjectNameFetcher::Name type {aytype.ToString()} is not supported");
        //     }
        //     cmd.CommandText = $"SELECT m.{COLUMN} FROM {TABLE} AS m WHERE m.id = {id} LIMIT 1";
        //     using (var dr = cmd.ExecuteReader())
        //         return dr.Read() ? dr.GetString(0) : "UNKNOWN";
        // }


        /*
                        2018-12-12 16:29:12.7547|INFO|Microsoft.EntityFrameworkCore.Database.Command|Executed DbCommand (3ms) [Parameters=[@__p_2='999', @__p_1='0'], CommandType='Text', CommandTimeout='30']
        SELECT a.id, a.active, a.xmin, a.count, a.dollaramount, a.enddate, a.name, a.notes, a.o wnerid, a.roles, a.serial, a.startdate, a.tags
        FROM (
            SELECT *, xmin FROM AWIDGET  where (name Like 'SortByFieldAscendingWorks 1544660950941%') ORDER BY startdate ASC
        ) AS a
        LIMIT @__p_2 OFFSET @__p_1

                         */


        /////////////////////////////////////////////////////////////////////

    }//eoc


}//eons

