using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

using GMLC01HerramientasCad.Logica;

using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System.Globalization;

namespace GMLC01HerramientasCad.Acad
{
    class LayerManagement
    {

        private LayerManagement()
        {
        }

        /// <summary>
        /// Si no existe, crea la capa indicada
        /// </summary>
        /// <remarks></remarks>
        public static void PrepareLayer(string layerName)
        {
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            //(command "_layer" "_t" "*" "")
            /*
             * doc.SendStringToExecute(
                  "(command \"_layer\" \"_t\" \"" + layerName + "\" \"\") ",
                  false, false, false);
             */
            Autodesk.AutoCAD.ApplicationServices.TransactionManager tm = doc.TransactionManager;

            Database db = doc.Database;
            //Al ser las paletas algo NO MODAL, para evitar un "eLockViolation" se debe bloquear el documento.
            using (DocumentLock docLock = Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                Transaction ta = db.TransactionManager.StartTransaction();
                try
                {
                    LayerTable tl = (LayerTable)tm.GetObject(db.LayerTableId, OpenMode.ForWrite, false);
                    LayerTableRecord ltRec = null;
                    bool changed = false;
                    if (!tl.Has(layerName))
                    {
                        ltRec = new LayerTableRecord();
                        ltRec.Name = layerName;
                        ltRec.Color = Autodesk.AutoCAD.Colors.Color.FromColor(GetColor4Layer(layerName));
                        tl.UpgradeOpen();
                        tl.Add(ltRec);
                        tm.AddNewlyCreatedDBObject(ltRec, true);
                    }
                    else
                    {
                        //tl.UpgradeOpen();
                        foreach (ObjectId lid in tl)
                        {
                            ltRec = (LayerTableRecord)ta.GetObject(lid.GetObject(OpenMode.ForWrite).ObjectId, OpenMode.ForWrite, true, true);
                            if (ltRec.Name.ToLower(CultureInfo.CurrentCulture) == layerName.ToLower(CultureInfo.CurrentCulture))
                            {
                                ltRec.UpgradeOpen();
                                if (ltRec.IsFrozen) { ltRec.IsFrozen = false; changed = true; }
                                if (ltRec.IsHidden) { ltRec.IsHidden = false; changed = true; }
                                if (ltRec.IsOff) { ltRec.IsOff = false; changed = true; }
                                if (ltRec.IsLocked) { ltRec.IsLocked = false; changed = true; }
                                break;
                            }
                        }
                    }
                    db.Clayer = ltRec.ObjectId;
                    if (changed)
                    {
                        tm.QueueForGraphicsFlush();
                        tm.FlushGraphics();
                        doc.Editor.UpdateScreen();
                    }
                    ta.Commit();
                }
                finally
                {
                    ta.Dispose();
                }
            }
        }

        private static System.Drawing.Color GetColor4Layer(string layerName)
        {
            // Abastecimiento
            if (layerName.ToLower(CultureInfo.CurrentCulture).StartsWith("a_", StringComparison.OrdinalIgnoreCase)) return System.Drawing.Color.FromArgb(0, 0, 255);
            // Saneamiento Pluvial
            if (layerName.ToLower(CultureInfo.CurrentCulture).StartsWith("s_pluv_", StringComparison.OrdinalIgnoreCase)) return System.Drawing.Color.FromArgb(0, 255, 255);
            // Saneamiento fecal
            if (layerName.ToLower(CultureInfo.CurrentCulture).StartsWith("s_resid_", StringComparison.OrdinalIgnoreCase)) return System.Drawing.Color.FromArgb(255, 63, 0);
            // Pavimentación y zona verde

            // Alumbrado público
            if (layerName.ToLower(CultureInfo.CurrentCulture).StartsWith("ap_", StringComparison.OrdinalIgnoreCase)) return System.Drawing.Color.FromArgb(255, 0, 0);
            // Electricidad
            if (layerName.ToLower(CultureInfo.CurrentCulture).StartsWith("el_", StringComparison.OrdinalIgnoreCase)) return System.Drawing.Color.FromArgb(68, 255, 5);
            // Telecomunicaciones
            if (layerName.ToLower(CultureInfo.CurrentCulture).StartsWith("t_", StringComparison.OrdinalIgnoreCase)) return System.Drawing.Color.FromArgb(255, 0, 191);
            // Gas
            if (layerName.ToLower(CultureInfo.CurrentCulture).StartsWith("g_", StringComparison.OrdinalIgnoreCase)) return System.Drawing.Color.FromArgb(204, 0, 51);
            // Riego
            if (layerName.ToLower(CultureInfo.CurrentCulture).StartsWith("r_", StringComparison.OrdinalIgnoreCase)) return System.Drawing.Color.FromArgb(51, 204, 0);

            // Otras capas
            return System.Drawing.Color.FromArgb(255, 255, 255);
        }

        public static Collection<string> GetModelLayers()
        {
            Collection<string> outCol = new Collection<string>();

            foreach (Categoria cat in ModComun.XSD.Categorias)
            {
                foreach (Entidad ent in cat.Entidades)
                {
                    outCol.Add(ent.Codigo.ToUpper(CultureInfo.CurrentCulture));
                    //System.Diagnostics.Debug.WriteLine(ent.Nombre + ": " + ent.Codigo);
                    if (ent.SubTipos != null)
                    {
                        foreach (SubTipo sbt in ent.SubTipos)
                        {
                            outCol.Add((ent.Codigo + "." + ent.CampoSubTipo + "." + sbt.Codigo).ToUpper(CultureInfo.CurrentCulture));
                        }
                    }
                }
            }
            return outCol;
        }


    }
}
