using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace pcmp
{
    public class HostScript
    {
        bool enablescript = false;
        object PythonEngine = null;
        Type TPythonEngine = null;
        MethodInfo miExecuteFile = null;
        PropertyInfo piGlobals = null;
        MethodInfo miGlobalsGet = null;

        public bool EnableScript
        {
            get { return enablescript; }
        }

        public HostScript()
        {
            string ironPythonPath = Path.Combine(Application.StartupPath, "IronPython.dll");
            if (!File.Exists(ironPythonPath))
            {
                Trace.WriteLine("IronPython.dllが見つかりませんでした");
                enablescript = false;
                return;
            }

            Assembly asm = Assembly.LoadFile(ironPythonPath);
            if (asm == null) return;
            TPythonEngine = asm.GetType("IronPython.Hosting.PythonEngine");
            if (TPythonEngine == null) return;
            miExecuteFile = TPythonEngine.GetMethod("ExecuteFile", new Type[] { typeof(string) });
            piGlobals = TPythonEngine.GetProperty("Globals", typeof(IDictionary<string, object>));
            miGlobalsGet = piGlobals.GetGetMethod();
            PythonEngine = Activator.CreateInstance(TPythonEngine);
            Trace.WriteLine("IronPythonスクリプトのサポート有効");
            enablescript = true;
        }

        public void ExecuteFile(string path)
        {
            if (miExecuteFile != null)
            {
                object[] param = { path };
                try
                {
                    Trace.WriteLine("IronPythonスクリプトを実行します : " + path);
                    miExecuteFile.Invoke(PythonEngine, param);
                }
                catch (Exception ex) { Trace.WriteLine(ex.Message); }
            }
        }

        public void AddGlobal(string name, object obj)
        {
            if (miGlobalsGet != null)
            {
                IDictionary<string, object> Globals = miGlobalsGet.Invoke(PythonEngine, null) as IDictionary<string, object>;
                if (Globals.ContainsKey(name)) Globals[name] = obj;
                else Globals.Add(name, obj);
            }
        }
    }
}
