using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using StarEngine.Core;
using StarEngine.Ruby;
using StarEngine.Sdl;

namespace StarEngine
{
    internal class Program
    {
        public static void Main()
        {
            try
            {
                if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
                {
                    MessageBox.Show("多重起動は出来ません。");
                    return;
                }

                Directory.SetCurrentDirectory("./Game");

                WindowType windowType = StarEngine.Properties.Settings.Default.WindowType;

                using (GameEnvironment env = GameEnvironment.Create(windowType))
                using (RubyInterpreter interpreter = RubyInterpreter.Create(env))
                {
                    interpreter.AddLoadPath("./Scripts");

                    string mainScriptPath = "./Scripts/main.rb";

                    string mainScript;
                    using (StreamReader reader = File.OpenText(mainScriptPath))
                        mainScript = reader.ReadToEnd();
                    
                    string mainScriptEscaped = mainScript.Replace("'", "\\'");

                    interpreter.Evaluate(
                        "begin\n" +
                        "  eval('" + mainScriptEscaped + "', binding, '" + mainScriptPath + "', 1)\n" +
                        "rescue Exception => e\n" +
                        "  puts(e.message)\n" +
                        "  puts(e.backtrace)\n" +
                        "  StarEngine::activate_console\n" +
                        "end");
                }
            }
            catch (Exception e)
            {
                using (CrashReportDialog crashReportDialog = new CrashReportDialog(e))
                    crashReportDialog.ShowDialog();
            }
        }
    }
}
