using System;
using System.Text.RegularExpressions;
using System.Web;
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 CustomStyles : Page
    {
		private readonly IFileStorageManager _fileStorageManager;
        private readonly IConfigurationManager _configurationManager;
        //private string customStylesName = "CustomStyles/customstyles.css";
        private const string customStylesFileName = "customstyles";
        private const string customStylesBundleDirectory = "CustomStyles";                

        public CustomStyles()
            : this(Ioc.Resolve<IFileStorageManager>(), Ioc.Resolve<IConfigurationManager>())
        {
        }

        public CustomStyles(IFileStorageManager fileStorageManager, IConfigurationManager configurationManager)
        {
			_fileStorageManager = fileStorageManager;
            _configurationManager = configurationManager;
        }

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

            var wizdomConfig = _configurationManager.GetWizdomConfiguration();

            var postfix = string.Empty;            
            var configCollection = wizdomConfig?.XPathSelectElements("/Config/CustomStyling");
            var configFilters = configCollection.Attributes("configFilter");
            var filterLength = 0;
            foreach (var configFilter in configFilters)
            {
                if (configFilter.Value.Length > filterLength && Regex.IsMatch(Request.UrlReferrer.ToString(), configFilter.Value, RegexOptions.IgnoreCase))
                {
                    postfix = HttpUtility.UrlEncode(configFilter.Value);
                    filterLength = configFilter.Value.Length;
                }
            }

            var res = _fileStorageManager.GetFile(customStylesBundleDirectory + "/" + customStylesFileName + postfix + ".css");
            if(res != null)
			    Response.Write(System.Text.Encoding.UTF8.GetString(res.Content));
		}

    }
}