unit DataMod;

interface

uses
  ExtCtrls,
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  Db, IBCustomDataSet, IBQuery, IBDatabase, IBEvents, FIBQuery, pFIBQuery,
  FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, frxDesgn, frxClass,
  frxDBSet, frxFIBComponents, frxDCtrl, variants, SIBEABase, SIBFIBEA;

type
  TDisconnectTimer = class(TTimer)
  public
    DisconnectTimeSec: Cardinal;
    constructor Create(AOwner: TComponent); override;
    procedure update;
    procedure setActive(value: boolean);
  private
    active: Boolean;
    time: Cardinal;
    db: TpFIBDatabase;
    procedure finish(Sender: TObject);
  end;

  Tdm = class(TDataModule)
    pFIBDbArc: TpFIBDatabase;
    pFIBTrnArc: TpFIBTransaction;
    QueryArc: TpFIBQuery;
    trnReadArc: TpFIBTransaction;
    pFIBDbMes: TpFIBDatabase;
    pFIBTrnMes: TpFIBTransaction;
    QueryMes: TpFIBQuery;
    trnReadMes: TpFIBTransaction;
    trnWriteMes: TpFIBTransaction;
    WrQueryMes: TpFIBQuery;
    dsRead: TpFIBDataSet;
    trnDsRead: TpFIBTransaction;
    frxDesigner: TfrxDesigner;
    frxReport: TfrxReport;
    frxFIBComponents: TfrxFIBComponents;
    frxDialogControls: TfrxDialogControls;
    evntMes: TSIBfibEventAlerter;
    frxDBDataset1: TfrxDBDataset;
    procedure evntMesEventAlert(Sender: TObject; EventName: String;
      EventCount: Integer);
    procedure DataModuleDestroy(Sender: TObject);
  private
  public
    function createDisconnectTimer(db: TpFIBDatabase; DisconnectTimeSec: Cardinal = 60): TDisconnectTimer;
  end;


var
  dm: Tdm;

implementation
uses
  MesLoggingV2;

{$R *.DFM}



procedure Tdm.evntMesEventAlert(Sender: TObject; EventName: String;
  EventCount: Integer);
begin
  if Trim(UpperCase(EventName)) = 'MESSAGES' then
    MesLoggingV2.onMessagesEvent;
end;

procedure Tdm.DataModuleDestroy(Sender: TObject);
begin
  dm := nil;
end;




function Tdm.createDisconnectTimer(db: TpFIBDatabase; DisconnectTimeSec: Cardinal): TDisconnectTimer;
begin
  result := TDisconnectTimer.Create(self);
  result.db := db;
  Result.DisconnectTimeSec := DisconnectTimeSec;
end;


{ TDisconnectTimer }

constructor TDisconnectTimer.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  active := true;
  Enabled := false;
  OnTimer := finish;
end;


procedure TDisconnectTimer.setActive(value: boolean);
begin
  if active <> value then begin
    active := value;
    if active then
      update
    else
      Enabled := False;
  end;
end;

procedure TDisconnectTimer.update;
begin
  if active then begin
    time := GetTickCount + 1000 * DisconnectTimeSec;

    if not Enabled then
      Enabled := True;
  end;
end;


procedure TDisconnectTimer.finish(Sender: TObject);
begin
  if time < GetTickCount then begin
    Enabled := false;
    try
      db.Close;
    except
    end;
  end;
end;

end.
