using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Security.Claims;
using FMSAdmin.Data;

namespace FMSAdmin.Helpers {
    public static class BusinessFieldHelper {

        public static IQueryable<T> Apply<T>(FMSContext context, ClaimsPrincipal user, bool businessAuth, IQueryable query, string prefix = "") {
            if (!businessAuth) return (IQueryable<T>)query;

            var usr = context.CmUser.FirstOrDefault(x => x.UserId == user.Identity.Name);
            if (usr == null) return (IQueryable<T>)query;

            string fieldName = "BusinessFieldId";
            if (!string.IsNullOrEmpty(prefix)) {
                fieldName = prefix + "." + fieldName;
            }

            var businessCommon = context.CmBusinessField.FirstOrDefault(x => x.Name == "공통");
            var businessCommonQuery = "";
            if (businessCommon != null) {
                businessCommonQuery = " OR " + fieldName + " == " + businessCommon.BusinessFieldId;
            }

            return (IQueryable<T>)query.Where("(" + fieldName + " == @0 " + businessCommonQuery + ")", usr.BusinessFieldId);
        }

    }
}
