using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Xml.Linq;
using System.Xml.XPath;
using Wizdom365.BLL.IoC;
using Wizdom365.BLL.Managers;

namespace GUI.Web.Base.Bundles
{
    public partial class CssGenerator : Page
    {
        private readonly IConfigurationManager _configurationManager;
		private readonly CssGeneratorManager _cssGeneratorManager;

        public CssGenerator()
            : this(Ioc.Resolve<IConfigurationManager>(), Ioc.Resolve<CssGeneratorManager>())
        {
        }

        public CssGenerator(IConfigurationManager configurationManager, CssGeneratorManager cssGeneratorManager)
        {
            _configurationManager = configurationManager;
			_cssGeneratorManager = cssGeneratorManager;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/css";

            var wizdomConfig = _configurationManager.GetWizdomConfiguration();

            XElement generatorXml = null;
            var cssGeneratorXmlCollection = wizdomConfig?.XPathSelectElements("/Config/CssGenerator");
            var configFilters = cssGeneratorXmlCollection.Attributes("configFilter");
            var filterLength = 0;
            foreach (var configFilter in configFilters)
            {
                if (configFilter.Value.Length > filterLength && Regex.IsMatch(Request.UrlReferrer.ToString(), configFilter.Value, RegexOptions.IgnoreCase))
                {
                    generatorXml = configFilter.Parent;
                    filterLength = configFilter.Value.Length;
                }
            }
            if (generatorXml == null)
                generatorXml = cssGeneratorXmlCollection.First();
                
            var selectedTheme = generatorXml?.XPathSelectElement("SelectedTheme")?.Value;                
            XElement themeCssItems = null;
            if (!String.IsNullOrEmpty(selectedTheme) && selectedTheme != "main")
            {
                var wizdomThemesXmlNode = wizdomConfig?.XPathSelectElement("/Config/WizdomThemes");
                if (wizdomThemesXmlNode != null)
                {
                    themeCssItems = wizdomThemesXmlNode.XPathSelectElement("Theme[@unigueId='" + selectedTheme + "']");
                }
            }
            XElement cssItems = generatorXml.XPathSelectElement("Styles");
            if (cssItems != null)
                Response.Write(_cssGeneratorManager.GenerateCss(cssItems, themeCssItems));
            

        }
    }
}