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 CustomScripts : Page
    {
		private readonly IFileStorageManager _fileStorageManager;
        private readonly IConfigurationManager _configurationManager;
        private const string defaultFileName = "customscripts";
        private const string dundleDirectory = "CustomJavascript";

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

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

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

            var wizdomConfig = _configurationManager.GetWizdomConfiguration();

            var postfix = string.Empty;
            var configCollection = wizdomConfig?.XPathSelectElements("/Config/CustomJs");
            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(dundleDirectory + "/" + defaultFileName + postfix + ".js");

            if (res != null)
                Response.Write(System.Text.Encoding.UTF8.GetString(res.Content));
		}
    }
}