unit sgBlockLibrary;

interface
uses
  Windows, DXFConv, DXFImage, sgConsts, Graphics, Classes, Controls,
  sgLines, Dialogs, SysUtils, sgDrawingNavigator;

type

  TsgBlockLibrary = class(TObject)
  private
    FDNavigator: TsgDrawingNavigator;
    FImg: TsgDXFImage;
    FConverter: TsgDXFConverter;
    FBlockList: TList;
    procedure SetImage(const Value: TsgDrawingNavigator);
  public
    constructor Create;
    destructor Destroy; override;
    procedure CopyAsBlock(AEnts: TList);
    function PasteAsBlock(Index: Integer; X, Y: Single): TsgDXFInsert;
    property DNavigator: TsgDrawingNavigator read FDNavigator write SetImage;
    property BlockList: TList read FBlockList;
  end;

implementation

{ TsgBlockLibrary }

constructor TsgBlockLibrary.Create;
begin
  inherited;
  FBlockList := TList.Create;
end;

destructor TsgBlockLibrary.Destroy;
var
  I: Integer;
begin
  for I := 0 to FBlockList.Count - 1 do
    TsgDXFBlock(FBlockList.Items[I]).Free;
  FBlockList.Free;
end;

procedure TsgBlockLibrary.SetImage(const Value: TsgDrawingNavigator);
begin
  FDNavigator := Value;
  FImg := TsgDXFImage(Value.Picture.Graphic);
  FConverter := FImg.Converter;
end;

procedure TsgBlockLibrary.CopyAsBlock(AEnts: TList);
var
  vBlock: TsgDXFBlock;
  vEnt: TsgDXFEntity;
  I: Integer;
begin
  vBlock := TsgDXFBlock.Create;
  vBlock.Name := '$'+IntToHex(Integer(Pointer(vBlock)),8);
  for I := 0 to AEnts.Count - 1 do
  begin
    vEnt := TsgDXFEntityClass(TsgDXFEntity(AEnts[I]).ClassType).Create;
    vEnt.AssignEntity(TsgDXFEntity(AEnts[I]));
    vBlock.AddEntity(vEnt);
  end;
  FBlockList.Add(vBlock);
end;

function TsgBlockLibrary.PasteAsBlock(Index: Integer; X, Y: Single): TsgDXFInsert;
var
  vBlock: TsgDXFBlock;
  I: Integer;
begin
  vBlock := TsgDXFBlock(FBlockList.Items[Index]);
  // If not loaded in Copy-method
  for I := 0 to vBlock.Count - 1 do
  begin
    FConverter.OnCreate(vBlock.Entities[I]);
    FConverter.Loads(vBlock.Entities[I]);
  end;
  FConverter.OnCreate(vBlock);
  FConverter.Sections[csBlocks].AddEntity(vBlock);
  FConverter.Loads(vBlock);
  Result := TsgDXFInsert.Create;
  FConverter.OnCreate(Result);
  Result.Block := vBlock;
  Result.Point := MakeFPoint(X, Y, 0);
  FConverter.Sections[csEntities].AddEntity(Result);
  FConverter.Loads(Result);
  FImg.GetExtents;
  FBlockList.Delete(Index);
  FDNavigator.Invalidate;
end;

end.
