unit uSesionesUtils;

interface

uses
  {VCL:} SysUtils, Contnrs, SyncObjs, Variants,
  {RemObjects}  uROSessions;

type

  TSesionesHelper = class
  private
    lObjects: TObjectList;
    csObjects: TCriticalSection;
    function  AddObject( aObj: TObject ) : integer;
    procedure  DeleteObject( aObj: TObject );
    function GetObject (aIndex : Integer) : TObject;
  public
    constructor Create;
    destructor  Destroy; override;
    function  GetSessionObject(aSession: TROSession; aObjName: string): TObject;
    procedure SaveSessionObject(aSession: TROSession; aObjName: string; aObj: TObject);
    procedure DeleteSessionObject(aSession: TROSession; aObjName: string);
  end;

var
  SesionesHelper: TSesionesHelper;

implementation

{ TSesionesHelper }

function TSesionesHelper.AddObject(aObj: TObject) : integer;
begin
  csObjects.Enter;
  try
    Result := lObjects.Add(aObj);
  finally
    csObjects.Leave;
  end;
end;

constructor TSesionesHelper.Create;
begin
  csObjects := TCriticalSection.Create;
  lObjects := TObjectList.Create;
end;

procedure TSesionesHelper.DeleteObject(aObj: TObject);
var
  idx: Integer;
begin
  csObjects.Enter;
  try
    idx := lObjects.IndexOf( aObj );
    if idx > -1 then
    begin
      lObjects.Remove(aObj);
    end;
  finally
    csObjects.Leave;
  end;
end;

procedure TSesionesHelper.DeleteSessionObject(aSession: TROSession;
  aObjName: string);
var
  oldObj: TObject;
begin
  oldObj := GetSessionObject(aSession, aObjName);
  if Assigned(oldObj) then
  begin
    DeleteObject( oldObj );
    aSession.Values[aObjName] := NULL;
  end;
end;

destructor TSesionesHelper.Destroy;
begin
  // Free class members
  FreeAndNil( lObjects );
  FreeAndNil( csObjects );
  inherited;
end;

function TSesionesHelper.GetObject(aIndex: Integer): TObject;
begin
  Result := NIL;
  csObjects.Enter;
  try
    if (AIndex > -1) and (AIndex < lObjects.Count) then
      Result := lObjects.Items[AIndex];
  finally
    csObjects.Leave;
  end;
end;

function TSesionesHelper.GetSessionObject(aSession: TROSession;
  aObjName: string): TObject;
var
  aValue : Variant;
begin
  Result := NIL;
  aValue := aSession.Values[aObjName];

  if VarIsType(aValue, varInteger) then
    Result := GetObject(aValue);
end;

// Saves a delhpi TObject to a session variable
procedure TSesionesHelper.SaveSessionObject(aSession: TROSession;
  aObjName: string; aObj: TObject);
var
  aIndex : Integer;
begin
  // Free the existing object if it has already been assigned
  DeleteSessionObject(aSession, aObjName);

  if Assigned( aObj ) then
    begin
      // Add the object name to the sessionobjectslist
      AIndex := AddObject(aObj);
      aSession.Values[aObjName] := AIndex;
    end
  else
    aSession.Values[aObjName] := NULL;
end;

initialization
  SesionesHelper := TSesionesHelper.Create;

finalization
  FreeAndNil( SesionesHelper );

end.
