using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using Kendo.Mvc.UI;
using Kendo.Mvc.UI.Fluent;
using Kreta.Web.Security;

namespace Kreta.Web.Helpers
{
    public static class DatePickerExtensions
    {
        public static DatePickerBuilder KretaDatePicker(this HtmlHelper helper, string id, string className = "", bool enabled = true, string culture = "hu-HU", DateTime? minValue = null, DateTime? maxValue = null, IDictionary<string, object> htmlAttributes = null)
        {
            if (helper.ViewData.ModelState[id] != null && helper.ViewData.ModelState[id].Errors.Count > 0)
                className = string.Format("{0} input-validation-error", className);

            var datepicker = helper.Kendo().DatePicker()
                .Name(id)
                .Enable(enabled)
                .Culture(culture);

            if (ClaimData.LCID == 1038 /*Magyar*/)
            {
                datepicker.Format("yyyy. MM. dd.");
            }

            if (!string.IsNullOrWhiteSpace(className) || !string.IsNullOrWhiteSpace(id))
            {
                var attributes = new Dictionary<string, object>();
                if (!string.IsNullOrWhiteSpace(className))
                    attributes.Add("class", className.Trim());
                if (!string.IsNullOrWhiteSpace(id))
                    attributes.Add("id", id);
                datepicker.HtmlAttributes(attributes);
            }

            if (minValue.HasValue)
                datepicker.Min(minValue.Value);
            if (maxValue.HasValue)
                datepicker.Max(maxValue.Value);
            if (htmlAttributes != null)
                datepicker.HtmlAttributes(htmlAttributes);

            return datepicker;
        }

        public static DatePickerBuilder KretaDatePickerFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes = null)
        {
            var fieldName = ExpressionHelper.GetExpressionText(expression);
            var fullBindingName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(fieldName);
            var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            var value = metadata.Model;

            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary<string, object>();
            }

            string displayName = metadata.DisplayName;
            bool isRequiredIf = false;
            string requiredIfMsg = "", requiredIfDepProperty = "", requiredIfDepOperator = "", requiredIfDepValue = "";

            fullBindingName = fullBindingName.Replace('.', '_');
            var validationAttributes = helper.GetUnobtrusiveValidationAttributes(fullBindingName, metadata);
            foreach (var attribute in validationAttributes)
            {
                var attributeValue = attribute.Value.ToString();
                switch (attribute.Key)
                {
                    case "data-val-required":
                        htmlAttributes.Add("data-rule-required", "true");
                        htmlAttributes.Add("data-msg-required", attributeValue);
                        htmlAttributes.Add("title", attributeValue);
                        displayName = metadata.DisplayName + " *";
                        break;
                    case "data-val-requiredif":
                        isRequiredIf = true;
                        requiredIfMsg = attributeValue;
                        displayName = metadata.DisplayName + " *";
                        break;
                    case "data-val-requiredif-dependentproperty":
                        requiredIfDepProperty = attributeValue;
                        break;
                    case "data-val-requiredif-operator":
                        requiredIfDepOperator = attributeValue;
                        break;
                    case "data-val-requiredif-dependentvalue":
                        requiredIfDepValue = attributeValue;
                        break;
                        //case "data-val-date":
                        //    htmlAttributes.Add("data-rule-date", "true");
                        //    htmlAttributes.Add("data-msg-date", attributeValue);
                        //    break;
                }
            }

            if (isRequiredIf)
            {
                htmlAttributes.Add("data-rule-requiredif", "{\"dependentproperty\":\"" + requiredIfDepProperty + "\",\"operator\":\"" + requiredIfDepOperator + "\",\"dependentvalue\":" + requiredIfDepValue.ToLower() + "}");
                htmlAttributes.Add("data-msg-requiredif", requiredIfMsg);
            }

            htmlAttributes.Add("data-labelmsg", displayName);
            //a dátum ellenőrzést fixen hozzáadjuk
            //htmlAttributes.Add("data-rule-date", "true");
            //htmlAttributes.Add("data-msg-date", string.Format(StringResourcesUtil.GetString(4297), metadata.DisplayName));

            var datePicker = (expression.ReturnType == typeof(DateTime))
                ? helper.Kendo().DatePickerFor(Expression.Lambda<Func<TModel, DateTime>>(expression.Body, expression.Parameters))
                : helper.Kendo().DatePickerFor(Expression.Lambda<Func<TModel, DateTime?>>(expression.Body, expression.Parameters));

            datePicker.HtmlAttributes(htmlAttributes);

            if (ClaimData.LCID == 1038 /*Magyar*/)
            {
                datePicker.Format("yyyy. MM. dd.");
            }

            return datePicker;
        }

        public static MvcHtmlString RenderSearchPanel(this DatePickerBuilder helper, bool withMask = true)
        {
            string labelMsg = "";
            foreach (var item in helper.ToComponent().HtmlAttributes)
            {
                if (item.Key == "data-labelmsg" && item.Value != null)
                    labelMsg = item.Value.ToString();
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("<div class=\"searchInputRowHeight\"><div>");
            sb.Append("<label class=\"searchPanelInputLabel\" for=\"").Append(helper.ToComponent().Name).Append("\">").Append(labelMsg).Append("</label>");
            sb.Append("</div><div>");
            sb.Append(helper.ToHtmlString());
            sb.Append("</div></div>");

            if (withMask)
                sb.Append("<script>$(\"#").Append(helper.ToComponent().Name.Replace('.', '_')).Append("\").kendoMaskedDatePicker();</script>");

            sb.Append("<script>$(\"#").Append(helper.ToComponent().Name.Replace('.', '_')).Append("\").change(function() { KretaDateTimeHelper.validateDate($(this)); });</script>");
            return new MvcHtmlString(sb.ToString());
        }

        public static MvcHtmlString RenderSearchPanelSideBar(this DatePickerBuilder helper, bool withMask = true)
        {
            string labelMsg = "";
            foreach (var item in helper.ToComponent().HtmlAttributes)
            {
                if (item.Key == "data-labelmsg" && item.Value != null)
                    labelMsg = item.Value.ToString();
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("<div class=\"searchPanelRow\">");
            sb.Append("<div class=\"searchPanelRowTitle\">");
            sb.Append("<label class=\"searchPanelLabel\" for=\"").Append(helper.ToComponent().Name).Append("\">").Append(labelMsg).Append("</label>");
            sb.Append("</div>");
            sb.Append("<div class=\"searchPanelRowValue\">");
            sb.Append(helper.ToHtmlString());
            sb.Append("</div>");
            sb.Append("</div>");

            if (withMask)
                sb.Append("<script>$(\"#").Append(helper.ToComponent().Name.Replace('.', '_')).Append("\").kendoMaskedDatePicker();</script>");

            sb.Append("<script>$(\"#").Append(helper.ToComponent().Name.Replace('.', '_')).Append("\").change(function() { KretaDateTimeHelper.validateDate($(this)); });</script>");
            return new MvcHtmlString(sb.ToString());
        }

        public static MvcHtmlString RenderWithMask(this DatePickerBuilder helper)
        {
            var controlId = helper.ToComponent().Id;

            var output = new StringBuilder();
            output.Append(helper.ToHtmlString());
            output.Append("<script>");
            output.Append($"$(\"#{controlId}\").kendoMaskedDatePicker();");
            output.Append($"$(\"#{controlId}\").change(function() {{ KretaDateTimeHelper.validateDate($(this)); }});");
            output.Append("</script>");

            return new MvcHtmlString(output.ToString());
        }

        public static MvcHtmlString RenderWithName(this DatePickerBuilder helper, int labelWidth = 6, int inputWidth = 6, bool allSizeSame = false, bool withMask = true, string tooltipResource = null, bool isCustomRequired = false, string labelMsg = null)
        {
            if (string.IsNullOrWhiteSpace(labelMsg))
            {
                foreach (var item in helper.ToComponent().HtmlAttributes)
                {
                    if (item.Key == "data-labelmsg" && item.Value != null)
                        labelMsg = item.Value.ToString();
                }
            }

            if (isCustomRequired)
                labelMsg += " *";

            var sb = new StringBuilder();

            if (string.IsNullOrWhiteSpace(tooltipResource))
                AddRenderWithNameBeginingFrame(sb, labelWidth, inputWidth, allSizeSame, helper.ToComponent().Name, labelMsg);
            else
                AddRenderWithNameTooltipBeginingFrame(sb, labelWidth, inputWidth, allSizeSame, helper.ToComponent().Name, labelMsg, tooltipResource);
            sb.Append(helper.ToHtmlString());
            AddRenderWithNameCloseingFrame(sb, withMask, helper.ToComponent().Name);

            return new MvcHtmlString(sb.ToString());
        }

        private static void AddRenderWithNameBeginingFrame(StringBuilder sb, int labelWidth, int inputWidth, bool allSizeSame, string controlName, string labelMsg)
        {
            sb.AppendFormat("<div class=\"{0}\">", BootsrapHelper.GetSizeClasses(labelWidth, allSizeSame));
            sb.AppendFormat("<label class=\"windowInputLabel\" for=\"{0}\">{1}</label>", controlName, labelMsg);
            sb.AppendFormat("</div><div class=\"{0} \">", BootsrapHelper.GetSizeClasses(inputWidth, allSizeSame));
        }

        private static void AddRenderWithNameTooltipBeginingFrame(StringBuilder sb, int labelWidth, int inputWidth, bool allSizeSame, string controlName, string labelMsg, string tooltipResource)
        {
            sb.AppendFormat("<div class=\"{0} kretaLabelTooltip \">", BootsrapHelper.GetSizeClasses(labelWidth, allSizeSame));
            sb.AppendFormat("<label class=\"windowInputLabel\" for=\"{0}\">{1}", controlName, labelMsg);
            sb.Append("&nbsp;<img class='kretaLabelTooltipImg' />");
            sb.AppendFormat("<span class=\"kretaLabelTooltipText\">{0}</span>", tooltipResource);
            sb.Append("</label>");
            sb.AppendFormat("</div><div class=\"{0} \">", BootsrapHelper.GetSizeClasses(inputWidth, allSizeSame));
        }

        private static void AddRenderWithNameCloseingFrame(StringBuilder sb, bool withMask, string controlName)
        {
            sb.Append("</div>");

            if (withMask)
                sb.AppendFormat("<script>$(\"#{0} \").kendoMaskedDatePicker();</script>", controlName.Replace('.', '_'));

            sb.Append("<script>$(\"#").Append(controlName.Replace('.', '_')).Append("\").change(function() { KretaDateTimeHelper.validateDate($(this)); });</script>");
        }

        public static MvcHtmlString RenderWithName(this DatePickerBuilder helper, string label, int labelWidth = 6, int inputWidth = 6, bool allSizeSame = false, bool withMask = true)
        {
            var sb = new StringBuilder();

            AddRenderWithNameBeginingFrame(sb, labelWidth, inputWidth, allSizeSame, helper.ToComponent().Name, label);
            sb.Append(helper.ToHtmlString());
            AddRenderWithNameCloseingFrame(sb, withMask, helper.ToComponent().Name);

            return new MvcHtmlString(sb.ToString());
        }
    }
}