unit SocketHandle;

interface

uses
  Windows, Classes, Controls, Forms, contnrs, Rubies, PSock;

type
  TSocketHandle = class(TObject)
  public
    procedure doConnect(Sender: TObject);
    procedure doDisconnect(Sender: TObject);
    procedure doPacketRecv(Sender: TObject);
    procedure doPacketSent(Sender: TObject);
    procedure doFailure(sock: TPowerSock; cmd: string);
    procedure doSuccess(sock: TPowerSock; cmd: string);
  end;

var
  cSocket: Tvalue;

function GetSocketHandle: TSocketHandle;

implementation

uses
{$IFDEF PHIEMBED}
  PhiMainUnit;
{$ELSE}
  Pythia;
{$ENDIF}

var
  Handle: TSocketHandle;

function GetSocketHandle: TSocketHandle;
begin
  result := Handle;
end;

procedure TSocketHandle.doConnect(Sender: TObject);
var
  recv, data: Tvalue;
begin
  recv := TComponent(Sender).tag;
  data := rb_ary_new;
  rb_ary_push(data, rb_intern('on_connect'));
  rb_ary_push(data, recv);
  PhiCallProtect(data);
end;

procedure TSocketHandle.doDisconnect(Sender: TObject);
var
  recv, data: Tvalue;
begin
  recv := TComponent(Sender).tag;
  data := rb_ary_new;
  rb_ary_push(data, rb_intern('on_disconnect'));
  rb_ary_push(data, recv);
  PhiCallProtect(data);
end;

procedure TSocketHandle.doPacketRecv(Sender: TObject);
var
  recv, data: Tvalue;
begin
  recv := cSocket; // TComponent(Sender).tag;
  data := rb_ary_new;
  rb_ary_push(data, rb_intern('on_packet_recv'));
  rb_ary_push(data, recv);
  PhiCallProtect(data);
end;

procedure TSocketHandle.doPacketSent(Sender: TObject);
var
  recv, data: Tvalue;
begin
  recv := cSocket; // TComponent(Sender).tag;
  data := rb_ary_new;
  rb_ary_push(data, rb_intern('on_packet_sent'));
  rb_ary_push(data, recv);
  PhiCallProtect(data);
end;

procedure TSocketHandle.doFailure(sock: TPowerSock; cmd: string);
var
  recv, data: Tvalue;
begin
  recv := sock.tag;
  data := rb_ary_new;
  rb_ary_push(data, rb_intern('on_failure'));
  rb_ary_push(data, recv);
  rb_ary_push(data, rb_str_new2(PChar(cmd)));
  PhiCallProtect(data);
end;

procedure TSocketHandle.doSuccess(sock: TPowerSock; cmd: string);
var
  recv, data: Tvalue;
begin
  recv := sock.tag;
  data := rb_ary_new;
  rb_ary_push(data, rb_intern('on_success'));
  rb_ary_push(data, recv);
  rb_ary_push(data, rb_str_new2(PChar(cmd)));
  PhiCallProtect(data);
end;

exports
  GetSocketHandle;

initialization
  Handle := TSocketHandle.Create;
finalization
  Handle.Free;
end.
