using System;
using System.ComponentModel.DataAnnotations;

namespace WK5.Core.Basis.Filter
{
    public class PaketFilter : Filter
    {
        [StringLength(2)]
        public PaketTyp Typ { get; set; }
        public string Nummer { get; set; } = String.Empty;
        public override string ToSqlQuery(FbController2 fbController)
        {
            sqlBuilder.Append(@"SELECT * FROM PAKETE WHERE 1 = 1 ");

            BuildQueryConditions(fbController);


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


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

            return sql;
        }

        protected override void BuildQueryConditions(FbController2 fbController)
        {
            sqlBuilder.Append(" AND PAKE_A_TYP = @PAKE_A_TYP");
            fbController.AddParameter("@PAKE_A_TYP", EnumHelper.GetPaketTypString(Typ));
            if (Typ is PaketTyp.Angebot or PaketTyp.Auftrag or PaketTyp.Lieferschein or PaketTyp.Rechnung or PaketTyp.RMA)
            {
                sqlBuilder.Append(" AND PAKE_N_BELENR = @PAKE_N_BELENR");
                fbController.AddParameter("@PAKE_N_BELENR", Nummer);
            }
            else
            {
                sqlBuilder.Append(" AND PAKE_A_KUNDNR = @PAKE_A_KUNDNR");
                fbController.AddParameter("@PAKE_A_KUNDNR", Nummer);
            }

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

                sqlBuilder.Append($@" AND 
(
   CAST(UPPER(PAKE_A_NOTIZ) AS VARCHAR(255)) LIKE @SUCHBEGRIFF 
OR CAST(UPPER(PAKE_A_NR) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(PAKE_A_EMP_NAME1) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(PAKE_A_EMP_NAME2) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(PAKE_A_EMP_NAME3) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(PAKE_A_EMP_STR) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(PAKE_A_EMP_LAND) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(PAKE_A_EMP_PLZ) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(UPPER(PAKE_A_EMP_ORT) AS VARCHAR(255)) LIKE @SUCHBEGRIFF
)");
                fbController.AddParameter("@SUCHBEGRIFF", $"%{Suchbegriff}%");
            }
        }
    }
}
