using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.Attributes;

namespace DemoCurtainGridPanelsTransactionBug
{
  [Transaction( TransactionMode.Manual )]
  [Regeneration( RegenerationOption.Manual )]
  public class TriggerCurtainGridPanelsTransactionBug 
    : IExternalCommand
  {
    /// <summary>
    /// Read in the walls of the document and try to 
    /// access panels in all CurtainWalls.
    /// </summary>
    public Result Execute( 
      ExternalCommandData commandData, 
      ref string message, 
      ElementSet elements )
    {
      var doc = commandData.Application
        .ActiveUIDocument.Document;

      var walls = new FilteredElementCollector( doc )
        .OfClass( typeof( Wall ) )
        .Cast<Wall>();

      foreach( var wall in walls )
      {
        if( wall.WallType.Kind == WallKind.Curtain )
        {
          TaskDialog.Show( 
            "CurtainGridPanelsTransactionBug",
            string.Format( 
              "CurtainWall has {0} panels.", 
              wall.CurtainGrid.Panels.Size ) );
        }
      }
      return Result.Succeeded;
    }
  }

  [Transaction( TransactionMode.Manual )]
  [Regeneration( RegenerationOption.Manual )]
  public class WorkAroundCurtainGridPanelsTransactionBug 
    : IExternalCommand
  {
    /// <summary>
    /// Read in the walls of the document and try to 
    /// access panels in all CurtainWalls.
    /// </summary>
    public Result Execute( 
      ExternalCommandData commandData, 
      ref string message, 
      ElementSet elements )
    {
      var doc = commandData.Application
        .ActiveUIDocument.Document;

      var walls = new FilteredElementCollector( doc )
        .OfClass( typeof( Wall ) )
        .Cast<Wall>();

      // workaround: create a transaction

      var transaction = new Transaction( doc, 
        "CurtainGridPanelsTransactionBug" );

      transaction.Start();

      try
      {
        foreach( var wall in walls )
        {
          if( wall.WallType.Kind == WallKind.Curtain )
          {
            TaskDialog.Show( 
              "CurtainGridPanelsTransactionBug",
              string.Format( 
                "CurtainWall has {0} panels.", 
                wall.CurtainGrid.Panels.Size ) );
          }
        }
      }
      finally
      {
        // we don't really want to change the document!

        transaction.RollBack();
      }
      return Result.Succeeded;
    }
  }
}
