// (C) Copyright 2010 by GEOGRAMA 
//
using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;

using GMLC01HerramientasCad.Logica;
using COMUN = GMLC01HerramientasCad.Logica;

// This line is not mandatory, but improves loading performances
[assembly: ExtensionApplication(typeof(GMLC01HerramientasCad.Acad.MyPlugin))]

namespace GMLC01HerramientasCad.Acad
{

    // This class is instantiated by AutoCAD once and kept alive for the 
    // duration of the session. If you don't do any one time initialization 
    // then you should remove this class.
    public class MyPlugin : IExtensionApplication
    {
        internal static string cultureName = "";

        internal static DibujarEnts dibujarElemento;
        internal static BuscarElementos buscarElementos;
        internal static Tematicos tematicos;
        internal static System.Collections.ObjectModel.Collection<string> modelLayers;
        internal static String modelLayersString;

        //private static bool booIgnoreEnteringQuiescentState;
        private static EventHandler eh;

        /// <summary>
        /// Recupera la carpeta en que se halla el ensamblado.
        /// </summary>
        /// <returns></returns>
        private static string AssemblyDirectory()
        {
            string codeBase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);
            return System.IO.Path.GetDirectoryName(path);
        }

        #region Miembros de IExtensionApplication


        public void Terminate()
        {
            try
            {
                //No code
            }
            catch (System.Exception ex)
            {
                Log.RegisterError(ex);
                throw new NotImplementedException("", ex);
            }
        }

        #endregion

        #region Miembros de IExtensionApplication

        public void Initialize()
        {
            try
            {
                IntInitialize();
            }
            catch (System.Exception ex)
            {
                Log.RegisterError(ex);
                throw new NotImplementedException("", ex);
            }
        }
        private static void IntInitialize()
        {
            try
            {
                ModComun.DirectorioConfiguracion = AssemblyDirectory();
                ModComun.CargarXSD("1.0.1");
            }
            finally
            {
            }

            // Si no se cargó el XSD, no se hará nada.
            if (ModComun.XSD == null)
            {
                System.Windows.Forms.MessageBox.Show(COMUN.Properties.Resources.ElFicheroXSDNoHaSidoCargado, "ERROR", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, System.Windows.Forms.MessageBoxDefaultButton.Button1, 0);
            }
            else
            {
                // Se recupera el listado completo de capas del modelo para posterior uso.
                modelLayers = LayerManagement.GetModelLayers();
                foreach (string s in modelLayers)
                {
                    modelLayersString += "," + s;
                }
                modelLayersString = modelLayersString.Trim(',');

                // Si es la primera ejecución del programa, se carga la barra de forma automática.
                string aRegKey = @"HKEY_CURRENT_USER\SOFTWARE\InventarioCAD\V2";
                string aRegValue = "FirstRun";
                if (Convert.ToInt32(Microsoft.Win32.Registry.GetValue(aRegKey, aRegValue, 0), System.Globalization.CultureInfo.InvariantCulture) == 0)
                {
                    //Change the value since the program has run once now
                    Microsoft.Win32.Registry.SetValue(aRegKey, aRegValue, 1, Microsoft.Win32.RegistryValueKind.DWord);                    
                    
                    eh = new EventHandler(EdEnteringQuiescentState);
                    Application.DocumentManager.MdiActiveDocument.Editor.EnteringQuiescentState += eh; //+= new System.EventHandler(   //(CallbackEnteringQuiescentState);
                    //Cui.CuiRebuild();
                }
            }
        }

        static void EdEnteringQuiescentState(object sender, EventArgs e)
        {
            //if (booIgnoreEnteringQuiescentState) return; //use booleans to allow you to ingore events when not needed.
            try
            {
                //do something
                Cui.CuiRebuild();
                Application.DocumentManager.MdiActiveDocument.Editor.EnteringQuiescentState -= eh;
                eh = null;
            }
            catch (System.Exception ex)
            {
                Log.RegisterError(ex);
                throw new COMUN.ExcepcionGMLC("", ex);
            }
        }
        #endregion
    }

    

}
