using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Umbraco.Core;
using Umbraco.Core.Logging;
using umbraco.cms.presentation.Trees;

namespace Umbraco.Web.Trees
{
    /// <summary>
    /// A class used to render the legacy JS requirements for trees and IActions.
    /// </summary>
    internal static class LegacyTreeJavascript
    {
        /// <summary>
        /// If any legacy tree requires any JS rendering then we will compile a JS output of the combination.
        /// </summary>
        /// <returns></returns>
        public static string GetLegacyTreeJavascript()
        {
            //find all tree defs that exists for the current application regardless of if they are active
            List<TreeDefinition> appTreeDefs = TreeDefinitionCollection.Instance;
            //Create the BaseTree's based on the tree definitions found
            var legacyTrees = appTreeDefs.Select(treeDef => treeDef.CreateInstance()).ToList();
            var javascript = new StringBuilder();
            foreach (var bTree in legacyTrees)
            {
                try
                {
                    bTree.RenderJS(ref javascript);
                }
                catch (Exception ex)
                {
                    LogHelper.Error(typeof(LegacyTreeJavascript), "Could not load the JS from the legacy tree " + bTree.TreeAlias, ex);
                }
            }

            return ReplaceLegacyJs(javascript.ToString());
        }

        /// <summary>
        /// Returns a string with javascript proxy methods for IActions that are using old javascript
        /// </summary>
        /// <returns></returns>
        public static string GetLegacyIActionJavascript()
        {
            var js = new StringBuilder();
            foreach (var a in ActionsResolver.Current.Actions.ToList())
            {
                // NH: Added a try/catch block to this as an error in a 3rd party action can crash the whole menu initialization
                try
                {
                    if (string.IsNullOrEmpty(a.Alias) == false && (string.IsNullOrEmpty(a.JsFunctionName) == false || string.IsNullOrEmpty(a.JsSource) == false))
                    {
                        // if the action is using invalid javascript we need to do something about this
                        if (global::umbraco.BusinessLogic.Actions.Action.ValidateActionJs(a) == false)
                        {
                            js.AppendLine("function IActionProxy_" + a.Alias.ToSafeAlias() + "() {");
                            js.AppendLine(global::umbraco.BusinessLogic.Actions.Action.ConvertLegacyJs(a.JsFunctionName));
                            js.AppendLine("}");
                        }
                    }
                }
                catch (Exception ee)
                {
                    LogHelper.Error(typeof(LegacyTreeJavascript), "Error initializing tree action", ee);
                }
            }

            if (js.Length != 0)
            {
                js.Insert(0, "// This javascript is autogenerated by Umbraco to ensure legacy compatiblity with old context menu items\n\n");
            }

            return ReplaceLegacyJs(js.ToString());
        }

        private static string ReplaceLegacyJs(string js){
            js = js.Replace("parent.right.document.location", "UmbClientMgr.getFakeFrame()");
            js = js.Replace("right.document.location", "UmbClientMgr.getFakeFrame()");

            return js;
        }
    }
}