using System.Collections.Generic;
using Autodesk.Revit;
using Autodesk.Revit.Elements;
using Autodesk.Revit.Symbols;
using Autodesk.Revit.Geometry;
using CmdResult = Autodesk.Revit.IExternalCommand.Result;

namespace CH_Revit
{
  public class CH_WallSiding : IExternalCommand
  {
    const double PRECISION = 0.00001;

    public CmdResult Execute(
      ExternalCommandData commandData,
      ref string message,
      ElementSet elements )
    {
      Application app = commandData.Application;
      Document doc = app.ActiveDocument;

      WallProfiles wps = new WallProfiles( app );

      if( !wps.Processing() )
        return CmdResult.Failed;

      Dictionary<XYZ, CurveArray> dictCa
        = new Dictionary<XYZ, CurveArray>();

      foreach( XYZ ori in wps.m_Profiles.Keys )
      {
        List<List<XYZ>> profile = wps.m_Profiles[ori];

        CurveArray ca = new CurveArray();

        for( int i = 0; i < profile.Count; i++ )
        {
          List<XYZ> pts = profile[i];

          for( int j = 0; j < pts.Count - 1; ++j )
          {
            ca.Append( 
              Line.get_Bound( pts[j], pts[j + 1] ) 
              as Curve );
          }
          ca.Append( 
            Line.get_Bound( pts[pts.Count - 1], pts[0] )
            as Curve );
        }

        dictCa.Add( ori, ca );
      }

      WallType wt = wps.SelectedSidingType 
        as WallType;

      Level lv = wps.m_Level;

      foreach( XYZ ori in dictCa.Keys )
      {
        try
        {
          Wall wa = doc.Create.NewWall( 
            dictCa[ori], wt, lv, false );

          double ang = wa.Orientation
            .Normalized.Angle( ori );
          
          if( ang > PRECISION )
            wa.flip();
        }
        catch
        {
          Util.InfoMsg( "cannot create the wall siding" );
          return CmdResult.Failed;
        }
      }
      return CmdResult.Succeeded;
    }
  }
}
