{$ifdef CPUX64}
  {$LIBSUFFIX '64'}
{$endif}

library OrderValidation;

{$R *.res}

uses
  Windows, SysUtils, AnsiStrings, System.Json;

const
  ORDER_VALIDATION_ERROR_LEN = 256;

function UserConnected(UserId, ErrorMsg: PAnsiChar): BOOL; stdcall;
begin
  Result := MessageBox(0,
    PChar(Format('Allow user %s to connect?', [UserId])),
      'Order Validation',
        MB_ICONQUESTION	or MB_YESNO or MB_SETFOREGROUND) = IDYES;
  if not Result then
    AnsiStrings.StrLCopy(ErrorMsg, PAnsiChar(AnsiStrings.Format('User %s access to TS denied!', [UserId])),
      ORDER_VALIDATION_ERROR_LEN - 1);
end;

procedure UserDisconnected(UserId: PAnsiChar); stdcall;
begin
  MessageBox(0, PChar(Format('User %s disconnected', [UserId])),
    'Order Validation', MB_ICONINFORMATION or MB_OK);
end;

// Obsolete. Old validation function
function ValidateOrder(UserId, TransName, Params, ErrorMsg: PAnsiChar): BOOL; stdcall;
begin
  Result := MessageBox(0,
    PChar(Format('Allow transaction %s from user %s with arguments "%s"?', [TransName, UserId, Params])),
      'Order Validation',
        MB_ICONQUESTION	or MB_YESNO or MB_SETFOREGROUND) = IDYES;
  if not Result then
    AnsiStrings.StrLCopy(ErrorMsg, PAnsiChar(AnsiStrings.Format('Transaction %s denied!', [TransName])),
      ORDER_VALIDATION_ERROR_LEN - 1);
end;

// Preferred. New validation function with JSON-format parameters.
function ValidateOrderEx(UserId, TransName, Params, JsonParams, ErrorMsg: PAnsiChar): BOOL; stdcall;
var
  Json: TJSONObject;
begin
  if JsonParams = nil then
    Result := ValidateOrder(UserId, TransName, Params, ErrorMsg)
  else begin
    Json := TJSONObject.Create;
    try
      Json.Parse(BytesOf(JsonParams), 0);
      Result := MessageBox(0,
        PChar(Format('Allow transaction %s from user %s with arguments "%s"?', [TransName, UserId, Json.ToString])),
          'Order Validation',
            MB_ICONQUESTION	or MB_YESNO or MB_SETFOREGROUND) = IDYES;
      if not Result then
        AnsiStrings.StrLCopy(ErrorMsg, PAnsiChar(AnsiStrings.Format('Transaction %s denied!', [TransName])),
          ORDER_VALIDATION_ERROR_LEN - 1);
    finally

    end;
  end;
end;

exports
  UserConnected name 'UserConnected',
  UserDisconnected name 'UserDisconnected',
  ValidateOrder name 'ValidateOrder',
  ValidateOrderEx name 'ValidateOrderEx';

end.

