<commit_before>﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using DNNConnect.CKEditorProvider.Constants;
using DNNConnect.CKEditorProvider.Objects;
using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;
using DotNetNuke.Security.Roles;

namespace DNNConnect.CKEditorProvider.Utilities
{

    /// <summary>
    /// Settings Base Helper Class
    /// </summary>
    public class SettingsUtil
    {
        #region Public Methods

        /// <summary>
        /// Checks the exists portal or page settings.
        /// </summary>
        /// <param name="editorHostSettings">The editor host settings.</param>
        /// <param name="key">The key.</param>
        /// <returns>
        /// Returns if Portal or Page Settings Exists
        /// </returns>
        internal static bool CheckExistsPortalOrPageSettings(List<EditorHostSetting> editorHostSettings, string key)
        {
            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))))
            {
                return
                    !string.IsNullOrEmpty(
                        editorHostSettings.FirstOrDefault(
                            setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))).Value);
            }

            // No Portal/Page Settings Found
            return false;
        }

        /// <summary>
        /// Checks there are any Module Settings
        /// </summary>
        /// <param name="moduleKey">The module key.</param>
        /// <param name="moduleId">The module id.</param>
        /// <returns>Returns if The Module Settings Exists or not.</returns>
        internal static bool CheckExistsModuleSettings(string moduleKey, int moduleId)
        {
            var hshModSet = new ModuleController().GetModuleSettings(moduleId);

            return hshModSet.Keys.Cast<string>().Any(key => key.StartsWith(moduleKey));
        }

        /// <summary>
        /// Checks the exists of the module instance settings.
        /// </summary>
        /// <param name="moduleKey">The module key.</param>
        /// <param name="moduleId">The module id.</param>
        /// <returns>Returns if The Module Settings Exists or not.</returns>
        internal static bool CheckExistsModuleInstanceSettings(string moduleKey, int moduleId)
        {
            var hshModSet = new ModuleController().GetModuleSettings(moduleId);

            return !string.IsNullOrEmpty((string)hshModSet[string.Format("{0}skin", moduleKey)]);
        }

        /// <summary>
        /// Loads the portal or page settings.
        /// </summary>
        /// <param name="portalSettings">The current portal settings.</param>
        /// <param name="currentSettings">The current settings.</param>
        /// <param name="editorHostSettings">The editor host settings.</param>
        /// <param name="key">The Portal or Page key.</param>
        /// <param name="portalRoles">The Portal Roles</param>
        /// <returns>
        /// Returns the Filled Settings
        /// </returns>
        internal static EditorProviderSettings LoadPortalOrPageSettings(
            PortalSettings portalSettings,
            EditorProviderSettings currentSettings,
            List<EditorHostSetting> editorHostSettings,
            string key,
            IList<RoleInfo> portalRoles)
        {
            var roles = new ArrayList();

            // Import all Editor config settings
            foreach (PropertyInfo info in GetEditorConfigProperties())
            {
                if (!editorHostSettings.Any(s => s.Name.Equals(string.Format("{0}{1}", key, info.Name))))
                {
                    continue;
                }

                /*if (!info.Name.Equals("CodeMirror") && !info.Name.Equals("WordCount"))
                {
                    continue;
                }*/

                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        setting => setting.Name.Equals(string.Format("{0}{1}", key, info.Name))).Value;

                if (string.IsNullOrEmpty(settingValue))
                {
                    continue;
                }

                switch (info.PropertyType.Name)
                {
                    case "String":
                        info.SetValue(currentSettings.Config, settingValue, null);
                        break;
                    case "Int32":
                        info.SetValue(currentSettings.Config, int.Parse(settingValue), null);
                        break;
                    case "Decimal":
                        info.SetValue(currentSettings.Config, decimal.Parse(settingValue), null);
                        break;
                    case "Boolean":
                        info.SetValue(currentSettings.Config, bool.Parse(settingValue), null);
                        break;
                }

                switch (info.Name)
                {
                    case "ToolbarLocation":
                        info.SetValue(
                            currentSettings.Config,
                            (ToolBarLocation)Enum.Parse(typeof(ToolBarLocation), settingValue),
                            null);
                        break;
                    case "DefaultLinkType":
                        info.SetValue(
                            currentSettings.Config,
                            (LinkType)Enum.Parse(typeof(LinkType), settingValue),
                            null);
                        break;
                    case "EnterMode":
                    case "ShiftEnterMode":
                        info.SetValue(
                            currentSettings.Config,
                            (EnterModus)Enum.Parse(typeof(EnterModus), settingValue),
                            null);
                        break;
                    case "ContentsLangDirection":
                        info.SetValue(
                            currentSettings.Config,
                            (LanguageDirection)Enum.Parse(typeof(LanguageDirection), settingValue),
                            null);
                        break;
                    case "CodeMirror":
                        foreach (var codeMirrorInfo in
                            typeof(CodeMirror).GetProperties()
                                .Where(codeMirrorInfo => !codeMirrorInfo.Name.Equals("Theme")))
                        {
                            switch (codeMirrorInfo.PropertyType.Name)
                            {
                                case "String":
                                    if (
                                        editorHostSettings.Any(
                                            s => s.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name))))
                                    {
                                        codeMirrorInfo.SetValue(currentSettings.Config.CodeMirror, settingValue, null);
                                    }

                                    break;
                                case "Boolean":
                                    if (
                                        editorHostSettings.Any(
                                            s => s.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name))))
                                    {
                                        codeMirrorInfo.SetValue(
                                            currentSettings.Config.CodeMirror,
                                            bool.Parse(settingValue),
                                            null);
                                    }

                                    break;
                            }
                        }

                        break;
                    case "WordCount":
                        foreach (var wordCountInfo in typeof(WordCountConfig).GetProperties())
                        {
                            switch (wordCountInfo.PropertyType.Name)
                            {
                                case "String":
                                    if (
                                        editorHostSettings.Any(
                                            s => s.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name))))
                                    {
                                        wordCountInfo.SetValue(currentSettings.Config.WordCount, settingValue, null);
                                    }

                                    break;
                                case "Boolean":
                                    if (
                                        editorHostSettings.Any(
                                            s => s.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name))))
                                    {
                                        wordCountInfo.SetValue(
                                            currentSettings.Config.WordCount,
                                            bool.Parse(settingValue),
                                            null);
                                    }

                                    break;
                            }
                        }

                        break;
                }
            }

            /////////////////

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.Skin = settingValue;
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.CodeMirror.Theme = settingValue;
                }
            }

            List<ToolbarRoles> listToolbarRoles = (from RoleInfo objRole in portalRoles
                                                   where
                                                       editorHostSettings.Any(
                                                           setting =>
                                                           setting.Name.Equals(
                                                               string.Format(
                                                                   "{0}{2}#{1}",
                                                                   key,
                                                                   objRole.RoleID,
                                                                   SettingConstants.TOOLB)))
                                                   where
                                                       !string.IsNullOrEmpty(
                                                           editorHostSettings.FirstOrDefault(
                                                               s =>
                                                               s.Name.Equals(
                                                                   string.Format(
                                                                       "{0}{2}#{1}",
                                                                       key,
                                                                       objRole.RoleID,
                                                                       SettingConstants.TOOLB))).Value)
                                                   let sToolbar =
                                                       editorHostSettings.FirstOrDefault(
                                                           s =>
                                                           s.Name.Equals(
                                                               string.Format(
                                                                   "{0}{2}#{1}",
                                                                   key,
                                                                   objRole.RoleID,
                                                                   SettingConstants.TOOLB))).Value
                                                   select
                                                       new ToolbarRoles { RoleId = objRole.RoleID, Toolbar = sToolbar })
                .ToList();

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    listToolbarRoles.Add(new ToolbarRoles { RoleId = -1, Toolbar = settingValue });
                }
            }

            currentSettings.ToolBarRoles = listToolbarRoles;

            var listUploadSizeRoles = (from RoleInfo objRole in portalRoles
                                       where
                                           editorHostSettings.Any(
                                               setting =>
                                               setting.Name.Equals(
                                                   string.Format(
                                                       "{0}{2}#{1}",
                                                       key,
                                                       objRole.RoleID,
                                                       SettingConstants.UPLOADFILELIMITS)))
                                       where
                                           !string.IsNullOrEmpty(
                                               editorHostSettings.FirstOrDefault(
                                                   s =>
                                                   s.Name.Equals(
                                                       string.Format(
                                                           "{0}{2}#{1}",
                                                           key,
                                                           objRole.RoleID,
                                                           SettingConstants.UPLOADFILELIMITS))).Value)
                                       let uploadFileLimit =
                                           editorHostSettings.FirstOrDefault(
                                               s =>
                                               s.Name.Equals(
                                                   string.Format(
                                                       "{0}{2}#{1}",
                                                       key,
                                                       objRole.RoleID,
                                                       SettingConstants.UPLOADFILELIMITS))).Value
                                       select
                                           new UploadSizeRoles { RoleId = objRole.RoleID, UploadFileLimit = Convert.ToInt32(uploadFileLimit) })
                .ToList();

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.UPLOADFILELIMITS))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.UPLOADFILELIMITS))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    listUploadSizeRoles.Add(new UploadSizeRoles { RoleId = -1, UploadFileLimit = Convert.ToInt32(settingValue) });
                }
            }

            currentSettings.UploadSizeRoles = listUploadSizeRoles;

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.ROLES))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.ROLES))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    string sRoles = settingValue;

                    currentSettings.BrowserRoles = sRoles;

                    string[] rolesA = sRoles.Split(';');

                    foreach (string sRoleName in rolesA)
                    {
                        if (Utility.IsNumeric(sRoleName))
                        {
                            RoleInfo roleInfo = RoleController.Instance.GetRoleById(portalSettings.PortalId, int.Parse(sRoleName));

                            if (roleInfo != null)
                            {
                                roles.Add(roleInfo.RoleName);
                            }
                        }
                        else
                        {
                            roles.Add(sRoleName);
                        }
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSER))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSER))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Browser = settingValue;

                    switch (currentSettings.Browser)
                    {
                        case "ckfinder":
                            foreach (string sRoleName in roles)
                            {
                                if (PortalSecurity.IsInRoles(sRoleName))
                                {
                                    currentSettings.BrowserMode = BrowserType.CKFinder;

                                    break;
                                }

                                currentSettings.BrowserMode = BrowserType.None;
                            }

                            break;
                        case "standard":
                            foreach (string sRoleName in roles)
                            {
                                if (PortalSecurity.IsInRoles(sRoleName))
                                {
                                    currentSettings.BrowserMode = BrowserType.StandardBrowser;

                                    break;
                                }

                                currentSettings.BrowserMode = BrowserType.None;
                            }

                            break;
                        case "none":
                            currentSettings.BrowserMode = BrowserType.None;
                            break;
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.INJECTJS))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.INJECTJS))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.InjectSyntaxJs = bResult;
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.WIDTH))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.WIDTH))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.Width = settingValue;
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HEIGHT))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HEIGHT))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.Height = settingValue;
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BLANKTEXT))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BLANKTEXT))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.BlankText = settingValue;
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CSS))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CSS))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.ContentsCss = settingValue;
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.Templates_Files = settingValue;
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.CustomJsFile = settingValue;
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CONFIG))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CONFIG))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.CustomConfig = settingValue;
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.FileListPageSize = int.Parse(settingValue);
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.FileListViewMode = (FileListView)Enum.Parse(typeof(FileListView), settingValue);
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.DefaultLinkMode = (LinkMode)Enum.Parse(typeof(LinkMode), settingValue);
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.UseAnchorSelector = bResult;
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.ShowPageLinksTabFirst = bResult;
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.OverrideFileOnUpload = bResult;
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SUBDIRS))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SUBDIRS))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.SubDirs = bResult;
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    try
                    {
                        currentSettings.BrowserRootDirId = int.Parse(settingValue);
                    }
                    catch (Exception)
                    {
                        currentSettings.BrowserRootDirId = -1;
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    try
                    {
                        currentSettings.UploadDirId = int.Parse(settingValue);
                    }
                    catch (Exception)
                    {
                        currentSettings.UploadDirId = -1;
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    try
                    {
                        currentSettings.ResizeWidth = int.Parse(settingValue);
                    }
                    catch (Exception)
                    {
                        currentSettings.ResizeWidth = -1;
                    }
                }
            }

            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT))))
            {
                var settingValue =
                    editorHostSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    try
                    {
                        currentSettings.ResizeHeight = int.Parse(settingValue);
                    }
                    catch (Exception)
                    {
                        currentSettings.ResizeHeight = -1;
                    }<commit_msg>Prevent unnecessary looping through cke settings<commit_after>﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using DNNConnect.CKEditorProvider.Constants;
using DNNConnect.CKEditorProvider.Objects;
using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security;
using DotNetNuke.Security.Roles;

namespace DNNConnect.CKEditorProvider.Utilities
{

    /// <summary>
    /// Settings Base Helper Class
    /// </summary>
    public class SettingsUtil
    {
        #region Public Methods

        /// <summary>
        /// Checks the exists portal or page settings.
        /// </summary>
        /// <param name="editorHostSettings">The editor host settings.</param>
        /// <param name="key">The key.</param>
        /// <returns>
        /// Returns if Portal or Page Settings Exists
        /// </returns>
        internal static bool CheckExistsPortalOrPageSettings(List<EditorHostSetting> editorHostSettings, string key)
        {
            if (
                editorHostSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))))
            {
                return
                    !string.IsNullOrEmpty(
                        editorHostSettings.FirstOrDefault(
                            setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))).Value);
            }

            // No Portal/Page Settings Found
            return false;
        }

        /// <summary>
        /// Checks there are any Module Settings
        /// </summary>
        /// <param name="moduleKey">The module key.</param>
        /// <param name="moduleId">The module id.</param>
        /// <returns>Returns if The Module Settings Exists or not.</returns>
        internal static bool CheckExistsModuleSettings(string moduleKey, int moduleId)
        {
            var hshModSet = new ModuleController().GetModuleSettings(moduleId);

            return hshModSet.Keys.Cast<string>().Any(key => key.StartsWith(moduleKey));
        }

        /// <summary>
        /// Checks the exists of the module instance settings.
        /// </summary>
        /// <param name="moduleKey">The module key.</param>
        /// <param name="moduleId">The module id.</param>
        /// <returns>Returns if The Module Settings Exists or not.</returns>
        internal static bool CheckExistsModuleInstanceSettings(string moduleKey, int moduleId)
        {
            var hshModSet = new ModuleController().GetModuleSettings(moduleId);

            return !string.IsNullOrEmpty((string)hshModSet[string.Format("{0}skin", moduleKey)]);
        }

        /// <summary>
        /// Loads the portal or page settings.
        /// </summary>
        /// <param name="portalSettings">The current portal settings.</param>
        /// <param name="currentSettings">The current settings.</param>
        /// <param name="editorHostSettings">The editor host settings.</param>
        /// <param name="key">The Portal or Page key.</param>
        /// <param name="portalRoles">The Portal Roles</param>
        /// <returns>
        /// Returns the Filled Settings
        /// </returns>
        internal static EditorProviderSettings LoadPortalOrPageSettings(
            PortalSettings portalSettings,
            EditorProviderSettings currentSettings,
            List<EditorHostSetting> editorHostSettings,
            string key,
            IList<RoleInfo> portalRoles)
        {
            var roles = new ArrayList();

            // Import all Editor config settings
            var props = GetEditorConfigProperties().ToList();
            var filteredSettings = editorHostSettings.Where(s => s.Name.StartsWith(key)).ToList();

            foreach (PropertyInfo info in props)
            {
                if (!filteredSettings.Any(s => s.Name.Equals(string.Format("{0}{1}", key, info.Name))))
                {
                    continue;
                }

                /*if (!info.Name.Equals("CodeMirror") && !info.Name.Equals("WordCount"))
                {
                    continue;
                }*/

                var settingValue =
                    filteredSettings.FirstOrDefault(
                        setting => setting.Name.Equals(string.Format("{0}{1}", key, info.Name))).Value;

                if (string.IsNullOrEmpty(settingValue))
                {
                    continue;
                }

                switch (info.PropertyType.Name)
                {
                    case "String":
                        info.SetValue(currentSettings.Config, settingValue, null);
                        break;
                    case "Int32":
                        info.SetValue(currentSettings.Config, int.Parse(settingValue), null);
                        break;
                    case "Decimal":
                        info.SetValue(currentSettings.Config, decimal.Parse(settingValue), null);
                        break;
                    case "Boolean":
                        info.SetValue(currentSettings.Config, bool.Parse(settingValue), null);
                        break;
                }

                switch (info.Name)
                {
                    case "ToolbarLocation":
                        info.SetValue(
                            currentSettings.Config,
                            (ToolBarLocation)Enum.Parse(typeof(ToolBarLocation), settingValue),
                            null);
                        break;
                    case "DefaultLinkType":
                        info.SetValue(
                            currentSettings.Config,
                            (LinkType)Enum.Parse(typeof(LinkType), settingValue),
                            null);
                        break;
                    case "EnterMode":
                    case "ShiftEnterMode":
                        info.SetValue(
                            currentSettings.Config,
                            (EnterModus)Enum.Parse(typeof(EnterModus), settingValue),
                            null);
                        break;
                    case "ContentsLangDirection":
                        info.SetValue(
                            currentSettings.Config,
                            (LanguageDirection)Enum.Parse(typeof(LanguageDirection), settingValue),
                            null);
                        break;
                    case "CodeMirror":
                        foreach (var codeMirrorInfo in
                            typeof(CodeMirror).GetProperties()
                                .Where(codeMirrorInfo => !codeMirrorInfo.Name.Equals("Theme")))
                        {
                            switch (codeMirrorInfo.PropertyType.Name)
                            {
                                case "String":
                                    if (
                                        filteredSettings.Any(
                                            s => s.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name))))
                                    {
                                        codeMirrorInfo.SetValue(currentSettings.Config.CodeMirror, settingValue, null);
                                    }

                                    break;
                                case "Boolean":
                                    if (
                                        filteredSettings.Any(
                                            s => s.Name.Equals(string.Format("{0}{1}", key, codeMirrorInfo.Name))))
                                    {
                                        codeMirrorInfo.SetValue(
                                            currentSettings.Config.CodeMirror,
                                            bool.Parse(settingValue),
                                            null);
                                    }

                                    break;
                            }
                        }

                        break;
                    case "WordCount":
                        foreach (var wordCountInfo in typeof(WordCountConfig).GetProperties())
                        {
                            switch (wordCountInfo.PropertyType.Name)
                            {
                                case "String":
                                    if (
                                        filteredSettings.Any(
                                            s => s.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name))))
                                    {
                                        wordCountInfo.SetValue(currentSettings.Config.WordCount, settingValue, null);
                                    }

                                    break;
                                case "Boolean":
                                    if (
                                        filteredSettings.Any(
                                            s => s.Name.Equals(string.Format("{0}{1}", key, wordCountInfo.Name))))
                                    {
                                        wordCountInfo.SetValue(
                                            currentSettings.Config.WordCount,
                                            bool.Parse(settingValue),
                                            null);
                                    }

                                    break;
                            }
                        }

                        break;
                }
            }

            /////////////////

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SKIN))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.Skin = settingValue;
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CODEMIRRORTHEME))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.CodeMirror.Theme = settingValue;
                }
            }

            List<ToolbarRoles> listToolbarRoles = (from RoleInfo objRole in portalRoles
                                                   where
                                                       filteredSettings.Any(
                                                           setting =>
                                                           setting.Name.Equals(
                                                               string.Format(
                                                                   "{0}{2}#{1}",
                                                                   key,
                                                                   objRole.RoleID,
                                                                   SettingConstants.TOOLB)))
                                                   where
                                                       !string.IsNullOrEmpty(
                                                           filteredSettings.FirstOrDefault(
                                                               s =>
                                                               s.Name.Equals(
                                                                   string.Format(
                                                                       "{0}{2}#{1}",
                                                                       key,
                                                                       objRole.RoleID,
                                                                       SettingConstants.TOOLB))).Value)
                                                   let sToolbar =
                                                       filteredSettings.FirstOrDefault(
                                                           s =>
                                                           s.Name.Equals(
                                                               string.Format(
                                                                   "{0}{2}#{1}",
                                                                   key,
                                                                   objRole.RoleID,
                                                                   SettingConstants.TOOLB))).Value
                                                   select
                                                       new ToolbarRoles { RoleId = objRole.RoleID, Toolbar = sToolbar })
                .ToList();

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.TOOLB))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    listToolbarRoles.Add(new ToolbarRoles { RoleId = -1, Toolbar = settingValue });
                }
            }

            currentSettings.ToolBarRoles = listToolbarRoles;

            var listUploadSizeRoles = (from RoleInfo objRole in portalRoles
                                       where
                                           filteredSettings.Any(
                                               setting =>
                                               setting.Name.Equals(
                                                   string.Format(
                                                       "{0}{2}#{1}",
                                                       key,
                                                       objRole.RoleID,
                                                       SettingConstants.UPLOADFILELIMITS)))
                                       where
                                           !string.IsNullOrEmpty(
                                               filteredSettings.FirstOrDefault(
                                                   s =>
                                                   s.Name.Equals(
                                                       string.Format(
                                                           "{0}{2}#{1}",
                                                           key,
                                                           objRole.RoleID,
                                                           SettingConstants.UPLOADFILELIMITS))).Value)
                                       let uploadFileLimit =
                                           filteredSettings.FirstOrDefault(
                                               s =>
                                               s.Name.Equals(
                                                   string.Format(
                                                       "{0}{2}#{1}",
                                                       key,
                                                       objRole.RoleID,
                                                       SettingConstants.UPLOADFILELIMITS))).Value
                                       select
                                           new UploadSizeRoles { RoleId = objRole.RoleID, UploadFileLimit = Convert.ToInt32(uploadFileLimit) })
                .ToList();

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.UPLOADFILELIMITS))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{2}#{1}", key, "-1", SettingConstants.UPLOADFILELIMITS))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    listUploadSizeRoles.Add(new UploadSizeRoles { RoleId = -1, UploadFileLimit = Convert.ToInt32(settingValue) });
                }
            }

            currentSettings.UploadSizeRoles = listUploadSizeRoles;

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.ROLES))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.ROLES))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    string sRoles = settingValue;

                    currentSettings.BrowserRoles = sRoles;

                    string[] rolesA = sRoles.Split(';');

                    foreach (string sRoleName in rolesA)
                    {
                        if (Utility.IsNumeric(sRoleName))
                        {
                            RoleInfo roleInfo = RoleController.Instance.GetRoleById(portalSettings.PortalId, int.Parse(sRoleName));

                            if (roleInfo != null)
                            {
                                roles.Add(roleInfo.RoleName);
                            }
                        }
                        else
                        {
                            roles.Add(sRoleName);
                        }
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSER))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSER))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Browser = settingValue;

                    switch (currentSettings.Browser)
                    {
                        case "ckfinder":
                            foreach (string sRoleName in roles)
                            {
                                if (PortalSecurity.IsInRoles(sRoleName))
                                {
                                    currentSettings.BrowserMode = BrowserType.CKFinder;

                                    break;
                                }

                                currentSettings.BrowserMode = BrowserType.None;
                            }

                            break;
                        case "standard":
                            foreach (string sRoleName in roles)
                            {
                                if (PortalSecurity.IsInRoles(sRoleName))
                                {
                                    currentSettings.BrowserMode = BrowserType.StandardBrowser;

                                    break;
                                }

                                currentSettings.BrowserMode = BrowserType.None;
                            }

                            break;
                        case "none":
                            currentSettings.BrowserMode = BrowserType.None;
                            break;
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.INJECTJS))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.INJECTJS))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.InjectSyntaxJs = bResult;
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.WIDTH))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.WIDTH))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.Width = settingValue;
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HEIGHT))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.HEIGHT))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.Height = settingValue;
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BLANKTEXT))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BLANKTEXT))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.BlankText = settingValue;
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CSS))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CSS))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.ContentsCss = settingValue;
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.TEMPLATEFILES))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.Templates_Files = settingValue;
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CUSTOMJSFILE))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.CustomJsFile = settingValue;
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CONFIG))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.CONFIG))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.Config.CustomConfig = settingValue;
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTPAGESIZE))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.FileListPageSize = int.Parse(settingValue);
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.FILELISTVIEWMODE))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.FileListViewMode = (FileListView)Enum.Parse(typeof(FileListView), settingValue);
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.DEFAULTLINKMODE))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    currentSettings.DefaultLinkMode = (LinkMode)Enum.Parse(typeof(LinkMode), settingValue);
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.USEANCHORSELECTOR))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.UseAnchorSelector = bResult;
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SHOWPAGELINKSTABFIRST))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.ShowPageLinksTabFirst = bResult;
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.OVERRIDEFILEONUPLOAD))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.OverrideFileOnUpload = bResult;
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SUBDIRS))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.SUBDIRS))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    bool bResult;
                    if (bool.TryParse(settingValue, out bResult))
                    {
                        currentSettings.SubDirs = bResult;
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.BROWSERROOTDIRID))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    try
                    {
                        currentSettings.BrowserRootDirId = int.Parse(settingValue);
                    }
                    catch (Exception)
                    {
                        currentSettings.BrowserRootDirId = -1;
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.UPLOADDIRID))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    try
                    {
                        currentSettings.UploadDirId = int.Parse(settingValue);
                    }
                    catch (Exception)
                    {
                        currentSettings.UploadDirId = -1;
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEWIDTH))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    try
                    {
                        currentSettings.ResizeWidth = int.Parse(settingValue);
                    }
                    catch (Exception)
                    {
                        currentSettings.ResizeWidth = -1;
                    }
                }
            }

            if (
                filteredSettings.Any(
                    setting => setting.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT))))
            {
                var settingValue =
                    filteredSettings.FirstOrDefault(
                        s => s.Name.Equals(string.Format("{0}{1}", key, SettingConstants.RESIZEHEIGHT))).Value;

                if (!string.IsNullOrEmpty(settingValue))
                {
                    try
                    {
                        currentSettings.ResizeHeight = int.Parse(settingValue);
                    }
                    catch (Exception)
                    {
                        currentSettings.ResizeHeight = -1;
                    }
{'fraction_non_alphanumeric': 0.08877288615820514, 'fraction_numerical': 0.00477356369627816, 'mean_word_length': 0.9294669915027631, 'pattern_counts': {'":': 36, '<': 93, '<?xml version=': 0, '>': 226, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 342, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4978299', 'n_tokens_mistral': 13669, 'n_tokens_neox': 12720, 'n_words': 2086}