unit TemplateManagerHelper;
// Export Templates To View

interface

uses
  ReportManager, ComCtrls, SysUtils;

type
  TTemplateManagerHelper = class
  private
    function FindClassTreeNode(ATreeView: TTreeView; AParent: TTreeNode; const AName: string): TTreeNode;
    function AddClassTreeNode(ATreeView: TTreeView; AParent: TTreeNode; const AName: string): TTreeNode;
    function GetClassTreeNode(ATreeView: TTreeView; AParent: TTreeNode; const AName: string): TTreeNode;

    procedure AddTemplateToTreeView(ATreeView: TTreeView; ATemplate: TTemplateNode);
  public
    procedure ExportToTreeView(ATreeView: TTreeView; ATemplates: TTemplateManager);
  end;

implementation

{ TTemplateManagerHelper }

function TTemplateManagerHelper.AddClassTreeNode(ATreeView: TTreeView;
  AParent: TTreeNode; const AName: string): TTreeNode;
begin
  Result := ATreeView.Items.AddChildObject(AParent, AName, Pointer(nil));
  Result.ImageIndex := -1;
  Result.SelectedIndex := -1;
end;

procedure TTemplateManagerHelper.AddTemplateToTreeView(
  ATreeView: TTreeView; ATemplate: TTemplateNode);
var
  vClassNode, vNode: TTreeNode;
begin
  vClassNode := GetClassTreeNode(ATreeView, nil, ATemplate.ClassNum + '.' + ATemplate.ClassName);
  if ATemplate.SubClassNum <> '' then
    vClassNode := GetClassTreeNode(ATreeView, vClassNode, ATemplate.SubClassNum + '.' + ATemplate.SubClassName);
  vNode := ATreeView.Items.AddChildObject(vClassNode, ATemplate.TemplateName, Pointer(ATemplate));
  vNode.ImageIndex := -1;
  vNode.SelectedIndex := -1;
end;

procedure TTemplateManagerHelper.ExportToTreeView(
  ATreeView: TTreeView; ATemplates: TTemplateManager);
var
  iTemplate: Integer;
  TemplateNode: TTemplateNode; 
  ClassNode: TTreeNode;
begin
  ATreeView.Items.Clear;
  for iTemplate := 0 to ATemplates.Count - 1 do
  begin
    TemplateNode := ATemplates.Template[iTemplate];
    AddTemplateToTreeView(ATreeView, TemplateNode);
  end;
  ATreeView.Items.AlphaSort(True);
end;

function TTemplateManagerHelper.FindClassTreeNode(ATreeView: TTreeView;
  AParent: TTreeNode; const AName: string): TTreeNode;
var
  I: Integer;
  vNode: TTreeNode;
begin
  Result := nil;
  if Assigned(AParent) then
    vNode := AParent.getFirstChild
  else
    vNode := ATreeView.Items.GetFirstNode;
  while not Assigned(Result) and Assigned(vNode) do
  begin
    if SameText(vNode.Text, AName) then
      Result := vNode;
    vNode := vNode.getNextSibling;
  end;
end;

function TTemplateManagerHelper.GetClassTreeNode(ATreeView: TTreeView;
  AParent: TTreeNode; const AName: string): TTreeNode;
begin
  Result := FindClassTreeNode(ATreeView, AParent, AName);
  if not Assigned(Result) then
    Result := AddClassTreeNode(ATreeView, AParent, AName);
end;

end.
