using System;
using System.Windows.Forms;
using ComponentPro;

namespace FunctionSample
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            FunctionSample();
        }

        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 concat 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;
        }

        public static void FunctionSample()
        {
            try
            {
                TemplateEngine dn = new TemplateEngine();
                dn.LoadFromString("Custom Pow Function demo: $x$ ^ $y$ = $Pow(x,y)$\r\nCustom String Concatenation: \"$str1$\" + \"$str2$\" = \"$Concat(str1, str2)$\"");
                dn.SetFunction("Pow", Power);
                dn.SetFunction("Concat", Concat);
                
                dn.SetValue("x", 15.0f);
                dn.SetValue("y", 2.3f);

                dn.SetValue("str1", "Hello ");
                dn.SetValue("str2", "World");

                MessageBox.Show(dn.Run());
            }
            catch (Exception exc)
            {
                MessageBox.Show("An exception occurred: " + exc.Message);
            }
        }
    }
}