unit ClientFormDBX;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ChannelID,
  DSClientRest, DSClientMetadata, DSProxyDelphiRest, DBXJSON, DBXDataSnap,
  DBXCommon, DSHTTPLayer, DB, SqlExpr,
  DSHTTPCommon, IndyPeerImpl;

type
  TFormClient = class(TForm)
    CallbackID: TLabel;
    btnRegisterCallback: TButton;
    btnUnregisterCallback: TButton;
    Memo1: TMemo;
    btnALARM: TButton;
    SQLConnection1: TSQLConnection;
    DSClientCallbackChannelManager1: TDSClientCallbackChannelManager;
    procedure FormCreate(Sender: TObject);
    procedure btnRegisterCallbackClick(Sender: TObject);
    procedure btnUnregisterCallbackClick(Sender: TObject);
    procedure btnALARMClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    procedure QueueLogValue(const AValue: string);
  protected
    { Protected declarations }
  public
    { Public declarations }
  end;

type
  TCallbackClient = class(TDBXCallback)
  private
    FChannelName: string;
    FCallbackName: string;
  public
    constructor Create(const AChannelName, ACallbackName: string);
    function Execute(const Arg: TJSONValue): TJSONValue; override;
  end;

var
  FormClient: TFormClient = nil;

implementation
uses
  ComObj;

{$R *.dfm}

procedure TFormClient.FormCreate(Sender: TObject);
begin
  DSClientCallbackChannelManager1.ChannelName := ChannelID.ChannelName;
  DSClientCallbackChannelManager1.ManagerId := CreateClassID;
  CallbackID.Caption := DSClientCallbackChannelManager1.ManagerId
end;

procedure TFormClient.QueueLogValue(const AValue: string);
begin
  TThread.Queue(nil,
    procedure
    begin
      Memo1.Lines.Add(AValue)
    end)
end;

procedure TFormClient.btnRegisterCallbackClick(Sender: TObject);
var
  Callback: TCallbackClient;
begin
  Callback := TCallbackClient.Create(ChannelName, CallbackID.Caption);
  DSClientCallbackChannelManager1.RegisterCallback(CallbackID.Caption, Callback);
end;

procedure TFormClient.btnUnregisterCallbackClick(Sender: TObject);
begin
  DSClientCallbackChannelManager1.UnregisterCallback(CallbackID.Caption);
end;

procedure TFormClient.btnALARMClick(Sender: TObject);
begin
  ChannelBroadCast(DSClientCallbackChannelManager1);
end;

procedure TFormClient.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  DSClientCallbackChannelManager1.UnregisterCallback(CallbackID.Caption);
end;

{ TCallbackClient }

constructor TCallbackClient.Create(const AChannelName, ACallbackName: string);
begin
  inherited Create;
  FChannelName := AChannelName;
  FCallbackName := ACallbackName;
end;

function TCallbackClient.Execute(const Arg: TJSONValue): TJSONValue;
begin
  if Assigned(FormClient) then
    FormClient.QueueLogValue(Format('Channel: %s, Callback: %s received %s', [
      FChannelName, FCallbackName, Arg.ToString]));
  Result := TJSONTrue.Create
end;

end.

