using System;

namespace WK5.Core.Basis.Filter
{
    public class AbgangFilter : PageFilter
    {
        public bool ZeitraumFiltern { get; set; }
        public DateTime Von { get; set; }
        public DateTime Bis { get; set; }
        public bool IsFilterActive
        {
            get
            {
                if (!String.IsNullOrWhiteSpace(Suchbegriff))
                {
                    return true;
                }

                return false;
            }
        }
        public override string ToCountQuery(FbController2 fbController)
        {
            sqlBuilder.AppendLine("SELECT COUNT(*) FROM ABGAENGE WHERE 1 = 1");
            BuildQueryConditions(fbController);
            string tmp = sqlBuilder.ToString();
            sqlBuilder.Clear();
            return tmp;
        }

        public override string ToSqlQuery(FbController2 fbController)
        {

            if (Suchbegriff.Length > 255)
            {
                throw new ArgumentOutOfRangeException(nameof(Suchbegriff), "Suchbegriff darf nicht länger als 255 Zeichen sein");
            }


            sqlBuilder.AppendLine($"SELECT FIRST {Limit} SKIP {(Seite - 1) * Limit} * FROM ABGAENGE WHERE 1 = 1");

            BuildQueryConditions(fbController);

            sqlBuilder.AppendLine(" ORDER BY ARAB_N_NR DESC");

            string tmp = sqlBuilder.ToString();
            sqlBuilder.Clear();
            return tmp;
        }

        protected override void BuildQueryConditions(FbController2 fbController)
        {

            if (!string.IsNullOrWhiteSpace(Suchbegriff))
            {
                sqlBuilder.AppendLine(@" AND 
(
    CAST(ARAB_N_NR AS VARCHAR(255)) LIKE @SUCHBEGRIFF
 OR CAST(ARAB_A_ARTIKEL AS VARCHAR(255)) LIKE @SUCHBEGRIFF
)");
                fbController.AddParameter("@SUCHBEGRIFF", $"%{Suchbegriff}%");
            }

            if (ZeitraumFiltern)
            {
                sqlBuilder.AppendLine(" AND ARAB_D_DATUM <= @VON AND ARAB_D_DATUM >= @BIS");
                fbController.AddParameter("@VON", Von.ToShortDateString());
                fbController.AddParameter("@BIS", Bis.ToShortDateString());
            }
        }
    }
}
