using System;
using ComponentPro;

namespace AdvancedDemo.Samples.Function_and_Property
{
    class Custom_Function : TemplateExampleBase
    {
        static object Power(TemplateEngine dt, object[] args)
        {
            // Function has two parameters
            if (!TemplateEngine.VerifyParameters(dt, "Pow", args, 2))
                return string.Empty;
            try
            {
                double x = Convert.ToDouble(args[0]);
                double y = Convert.ToDouble(args[1]);
                return Math.Pow(x, y);
            }
            catch (Exception exc)
            {
                dt.WriteError("Invalid parameter, error: " + exc.Message);
                return string.Empty;
            }
        }

        /// <summary>
        /// Although TemplateEngine already provided a powerful + operator for string object, we purposely create a function to concatenate two strings for demonstration only.
        /// </summary>
        static object Concat(TemplateEngine dt, object[] args)
        {
            // Function has two parameters in string type.
            if (!TemplateEngine.VerifyParameters(dt, "Concat", args, 2, typeof(string), typeof(string)))
                return string.Empty;
            string s1 = args[0] as string;
            string s2 = args[1] as string;
            return s1 + s2;
        }

        /// <summary>
        /// Generates output from a template file.
        /// </summary>
        /// <param name="templateSourceDirectory">The path to the directory that contains the template file.</param>
        /// <param name="templateFile">The template file path.</param>
        /// <param name="templateSource">The template source loaded from the template file.</param>
        /// <returns>The generated output.</returns>
        public override string Generate(string templateSourceDirectory, string templateFile, string templateSource)
        {
            // Create a new instance of the TemplateEngine class.
            TemplateEngine dt = new TemplateEngine();

            // Load template content from a file.
            dt.LoadFromString(templateSource);
            dt.SetValue("TemplateSourceDirectory", templateSourceDirectory);

            dt.SetFunction("Pow", Power);
            dt.SetFunction("Concat", Concat);

            dt.SetValue("x", 15.0f);
            dt.SetValue("y", 2.3f);
            dt.SetValue("str1", "Hello ");
            dt.SetValue("str2", "World");

            // Generate output.
            string output = dt.Run();

            return output;
        }
    }
}
