using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using DXGfxLib;

namespace Editor
{
    public delegate void NewScene(string fileName, Object obj);
    public delegate void MeshAdded(string fileName, Object obj);
    public delegate void MeshRemoved(string fileName, Object obj);
    public delegate void Select(string name, Object obj);

    public class Mediator
    {
        private static Mediator globalInstance = null;

        public static Editor.MainForm mainForm = null;


        public DXGfxLib.Scene currentScene = null;
        public DXGfxLib.SceneNode selectedNode = null;
        public IAmScriptable selectedScriptableObj = null;


        public Mediator(Editor.MainForm main)
        {
            if(globalInstance!=null)
            {
                throw new Exception("There should not be any more than one instance of the Mediator per app! This operation is not allowed!");
            }

            mainForm = main;
        }

        public static Mediator GetGlobalInstance()
        {
            return globalInstance;
        }

        public event NewScene OnNewScene;

        public void NewScene(string fileName, DXGfxLib.Scene scene)
        {
            if (OnNewScene != null)
            {
                OnNewScene(fileName, scene);
            }
            currentScene = scene;
            if (currentScene != null)
            {
                Select(currentScene.name, currentScene);
            }
            else
            {
                Select("fileName", currentScene);
            }
        }

        public event MeshAdded OnMeshAdded;
        public event MeshRemoved OnMeshRemoved;

        public void MeshAdded(string fileName, DXGfxLib.SceneNode obj)
        {
            if (OnMeshAdded != null)
            {
                OnMeshAdded(fileName, obj);
            }
            Select(obj.name, obj);
        }

        public void MeshRemoved(string fileName, DXGfxLib.SceneNode obj)
        {
            if (OnMeshRemoved != null)
            {
                OnMeshRemoved(fileName, obj);
            }
            Select(currentScene.name, currentScene);
        }

        public event Select OnSelect;

        public void Select(string name, Object obj)
        {
            // Save scripts!
            if (selectedScriptableObj != null)
            {
                mainForm.SaveScripts(selectedScriptableObj);
                mainForm.SaveTimeLine(selectedScriptableObj);
            }

            if (OnSelect != null)
            {
                OnSelect(name, obj);
            }

            selectedScriptableObj = obj as IAmScriptable;
            selectedNode = obj as SceneNode;
        }
    }
}
