using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using AcRx = Autodesk.AutoCAD.Runtime;
using AcAp = Autodesk.AutoCAD.ApplicationServices;
using AcDb = Autodesk.AutoCAD.DatabaseServices;
using AcGe = Autodesk.AutoCAD.Geometry;
using AcEd = Autodesk.AutoCAD.EditorInput;
 
// This line is not mandatory, but improves loading performances
[assembly: CommandClass(typeof(TestRename.MyCommands))]
 
namespace TestRename
{
  public class MyCommands
  {
    [CommandMethod("RenBlock")]
    public void RenBlock()
    {
      AcAp.Document doc = AcAp.Application.DocumentManager.MdiActiveDocument;
      AcEd.Editor ed = doc.Editor;
      AcEd.PromptEntityOptions pr1 =
        new AcEd.PromptEntityOptions("\nУкажите вставку блока для переименования: ");
      pr1.SetRejectMessage("Это не вставка блока!");
      pr1.AddAllowedClass(typeof(AcDb.BlockReference), true);
      AcEd.PromptEntityResult res1 = ed.GetEntity(pr1);
      if (res1.Status != AcEd.PromptStatus.OK) return;
      AcDb.ObjectId idBtr = AcDb.ObjectId.Null;
      bool isDynamic = false;
      bool isUnnamed = false;
      string old_name;
      using (AcDb.BlockReference br =
        res1.ObjectId.Open(AcDb.OpenMode.ForRead) as AcDb.BlockReference)
      {
        idBtr = br.BlockTableRecord;
        isDynamic = br.IsDynamicBlock;
        using (AcDb.BlockTableRecord btr =
          idBtr.Open(AcDb.OpenMode.ForRead) as AcDb.BlockTableRecord)
        {
          old_name = btr.Name;
          isUnnamed = btr.IsAnonymous;
        }
      }
      AcEd.PromptStringOptions pr2 =
        new AcEd.PromptStringOptions("\nУкажите новое имя блока: ");
      pr2.DefaultValue = old_name;
 
      AcEd.PromptResult res2 = ed.GetString(pr2);
      if (res2.Status != AcEd.PromptStatus.OK) return;
 
      string new_name = res2.StringResult;
 
      if (String.Compare(new_name, old_name, true) == 0) return;
      if (AcDb.SymbolUtilityServices.ValidateCompatibleSymbolName(
         new_name, true, false,
         AcDb.SymbolUtilityServices.IsCompatibilityMode(doc.Database)) != AcRx.ErrorStatus.OK)
      {
        ed.WriteMessage("\nНедопустимое имя для блока \'{0}\'!", new_name);
        return;
      }
      if (isDynamic && isUnnamed)
      {
        using (AcDb.BlockTableRecord btr =
          idBtr.Open(AcDb.OpenMode.ForRead) as AcDb.BlockTableRecord)
        {
          try
          {
            AcDb.ObjectId idBtrNew = AcDb.ObjectId.Null;
            using (AcDb.BlockTableRecord btr_new = new AcDb.BlockTableRecord())
            {
              btr_new.Name = new_name;
              // btr_new.CopyFrom(btr);
              btr_new.Origin = btr.Origin;
              btr_new.BlockScaling = btr.BlockScaling;
              btr_new.Annotative = btr.Annotative;
              btr_new.Units = btr.Units;
              using (AcDb.BlockTable bt = doc.Database.BlockTableId.Open(AcDb.OpenMode.ForWrite) as AcDb.BlockTable)
              {
                idBtrNew = bt.Add(btr_new);
              }
            }
            AcDb.ObjectIdCollection ids = new AcDb.ObjectIdCollection();
            foreach (AcDb.ObjectId id in btr) ids.Add(id);
            AcDb.IdMapping map = new AcDb.IdMapping();
            doc.Database.DeepCloneObjects(ids, idBtrNew, map, true);
            using (AcDb.BlockReference br =
              res1.ObjectId.Open(AcDb.OpenMode.ForWrite) as AcDb.BlockReference)
            {
              br.BlockTableRecord = idBtrNew;
            }
          }
          catch
          {
            ed.WriteMessage("\nБлок \'{0}\' нельзя переименовать в \'{1}\'!",
              old_name, new_name);
          }
        }
      }
      else
      {
        using (AcDb.BlockTableRecord btr =
          idBtr.Open(AcDb.OpenMode.ForWrite) as AcDb.BlockTableRecord)
        {
          try
          {
            btr.Name = new_name;
          }
          catch
          {
            ed.WriteMessage("\nБлок \'{0}\' нельзя переименовать в \'{1}\'!",
              old_name, new_name);
          }
        }
      }
    }
  }
}