unit MainFormURL;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Generics.Collections,
  Aurelius.Drivers.Interfaces,
  Aurelius.Drivers.SQLite,
  Aurelius.Sql.SQLite,
  Aurelius.Schema.SQLite,
  Sparkle.HttpSys.Server,
  XData.Aurelius.ConnectionPool,
  XData.Server.Module, System.Actions, Vcl.ActnList, Vcl.ComCtrls, Vcl.ExtCtrls,
  ServerByUrl.Module;

type
  TForm1 = class(TForm)
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    Panel2: TPanel;
    ListBox1: TListBox;
    Button1: TButton;
    Button2: TButton;
    ActionList1: TActionList;
    acAddDatabase: TAction;
    acRemoveDatabase: TAction;
    Button3: TButton;
    procedure acAddDatabaseExecute(Sender: TObject);
    procedure acRemoveDatabaseExecute(Sender: TObject);
    procedure acRemoveDatabaseUpdate(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    FServers: TDictionary<string, TServerByUrlModule>;
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.acAddDatabaseExecute(Sender: TObject);
var
  Server: TServerByUrlModule;
  DBName: string;
begin
  if not InputQuery('Add Database', 'Enter database name:', DBName) then Exit;
  if ListBox1.Items.IndexOf(DBName) >= 0 then
    raise Exception.Create('Database already exists.');
  if DBName = '' then
    raise Exception.Create('Database name cannot be empty');

  Server := TServerByUrlModule.Create(nil);
  FServers.Add(DBName, Server);
  ListBox1.Items.Add(DBName);
  Server.StartServer(DBName);
end;

procedure TForm1.acRemoveDatabaseExecute(Sender: TObject);
begin
  FServers.Remove(ListBox1.Items[ListBox1.ItemIndex]);
  ListBox1.Items.Delete(ListBox1.ItemIndex);
end;

procedure TForm1.acRemoveDatabaseUpdate(Sender: TObject);
begin
  acRemoveDatabase.Enabled := ListBox1.ItemIndex >= 0;
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  ShowMessage(
    'This demo shows how to create a multi-tenant TMS XData Server.' + sLineBreak + sLineBreak +
    'The API has multiple endpoint URL: ' + sLineBreak +
    'http://localhost:2001/tms/multitenant/database1' + sLineBreak +
    'http://localhost:2001/tms/multitenant/database2' + sLineBreak + sLineBreak +
    'Clients choose the database to access by using the proper URL'
  );
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FServers := TObjectDictionary<string, TServerByUrlModule>.Create([doOwnsValues]);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FServers.Free;
end;

end.
