using System;

namespace WK5.Core.Basis.Filter
{
    public class SeriennummerFilter : Filter
    {
        public string Artikelnummer { get; set; } = String.Empty;
        public bool NurNichtAusgelieferte { get; set; }
        public override string ToSqlQuery(FbController2 fbController)
        {
            sqlBuilder.Append("SELECT * FROM VIEW_SN WHERE 1 = 1");
            BuildQueryConditions(fbController);

            sqlBuilder.Append(" ORDER BY ZUGA_D_DATUM DESC");

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

        protected override void BuildQueryConditions(FbController2 fbController)
        {
            if (!String.IsNullOrWhiteSpace(Artikelnummer))
            {
                sqlBuilder.Append(" AND CHAR_A_ARTINR = @CHAR_A_ARTINR");
                fbController.AddParameter("@CHAR_A_ARTINR", Artikelnummer);
            }

            if (NurNichtAusgelieferte)
            {
                sqlBuilder.Append(" AND SNNR_L_AUSGELIEFERT = 'N'");
            }

            if (!String.IsNullOrWhiteSpace(Suchbegriff))
            {
                if (Suchbegriff.Length > 255)
                {
                    throw new ArgumentOutOfRangeException(nameof(Suchbegriff));
                }

                sqlBuilder.Append(@" AND 
(
   CAST(SNNR_A_SN AS VARCHAR(255)) LIKE @SUCHBEGRIFF 
OR CAST(LIEF_A_NAME1 AS VARCHAR(255)) LIKE @SUCHBEGRIFF 
)");
                fbController.AddParameter("@SUCHBEGRIFF", $"%{Suchbegriff}%");
            }
        }
    }
}
