using System;

namespace WK5.Core.Basis.Filter
{
    public class LieferantenArtikelFilter : PageFilter
    {
        public int Lieferantennummer { get; set; }
        public bool InaktiveAnzeigen { get; set; } = false;


        public override string ToCountQuery(FbController2 fbController)
        {
            sqlBuilder.Append($"SELECT COUNT(*) FROM ARTIKEL");

            BuildQueryConditions(fbController);



            string sql = sqlBuilder.ToString();
            sqlBuilder.Clear();

            return sql;
        }
        public override string ToSqlQuery(FbController2 fbController)
        {
            sqlBuilder.Append($"SELECT FIRST {Limit} SKIP {(Seite - 1) * Limit} ARLI_A_ARTIKELNR FROM ARTIKEL");

            BuildQueryConditions(fbController);

            sqlBuilder.Append(" ORDER BY ARLI_A_ARTIKELNR ASC");

            string sql = sqlBuilder.ToString();
            sqlBuilder.Clear();

            return sql;
        }

        protected override void BuildQueryConditions(FbController2 fbController)
        {
            sqlBuilder.Append(" LEFT JOIN LIEFERANTENARTIKEL ON ARTI_A_NR = ARLI_A_ARTIKELNR WHERE ARLI_N_LIEFNR = @ARLI_N_LIEFNR ");

            fbController.AddParameter("@ARLI_N_LIEFNR", Lieferantennummer);
            if (!String.IsNullOrWhiteSpace(Suchbegriff))
            {
                if (Suchbegriff.Length > 255)
                {
                    throw new ArgumentOutOfRangeException(nameof(Suchbegriff));
                }

                sqlBuilder.Append(@$" AND 
(
CAST(UPPER(ARLI_A_ARTIKELNR) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(ARLI_A_BEZ1) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(ARLI_A_BEZ2) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(ARLI_A_BEZ3) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(ARLI_A_BEZ4) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(ARLI_A_BEZ5) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(ARLI_A_BESTELLNR) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
)");
                fbController.AddParameter("@SUCHBEGRIFF", $"%{Suchbegriff}%");
            }

            if (!InaktiveAnzeigen)
            {
                sqlBuilder.Append(" AND ARTI_L_INAKTIV = 'N'");
            }
        }
    }

}
