using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WK5.Core.Basis.Filter
{
    public class WartungFilter : PageFilter
    {
        public bool ZeigeErledigte { get; set; }

        public bool IsFilterActive
        {
            get
            {
                if(!String.IsNullOrWhiteSpace(Suchbegriff))
                {
                    return true;
                }

                if(ZeigeErledigte)
                {
                    return true;
                }

                return false;
            }
        }
        public override string ToCountQuery(FbController2 fbController)
        {
            sqlBuilder.Append($@"SELECT COUNT(*) 
FROM WARTUNGEN W
LEFT JOIN KUNDEN K ON K.KUND_A_NR = W.WART_A_KUNDENNR
WHERE 1 = 1");
            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} 
W.*, 
KUND_A_NAME1, KUND_L_KEINE_WARTUNGEN
FROM WARTUNGEN W
LEFT JOIN KUNDEN K ON K.KUND_A_NR = W.WART_A_KUNDENNR
WHERE 1 = 1");
            BuildQueryConditions(fbController);
            sqlBuilder.Append(" ORDER BY WART_N_NR DESC");

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

        protected override void BuildQueryConditions(FbController2 fbController)
        {
            if(!ZeigeErledigte)
            {
                sqlBuilder.Append(" AND WART_L_ERLEDIGT = 'N'");
            }

            if(!String.IsNullOrWhiteSpace(Suchbegriff))
            {
                sqlBuilder.Append(@" AND 
(
   CAST(WART_N_NR AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(WART_A_KUNDENNR AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(WART_A_ARTIKELNR AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR CAST(WART_A_SN AS VARCHAR(255)) LIKE @SUCHBEGRIFF
OR COALESCE(CAST(KUND_A_NAME1 AS VARCHAR(255)), '') LIKE @SUCHBEGRIFF
)");
                fbController.AddParameter("@SUCHBEGRIFF", $"%{Suchbegriff}%");
            }
        }
    }
}
