unit fMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Winapi.ShellApi,
  System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
  Vcl.StdCtrls, dServer;

type
  TMainForm = class(TForm)
    mmInfo: TMemo;
    btStart: TButton;
    btStop: TButton;
    btSwaggerUI: TButton;
    procedure btStartClick(ASender: TObject);
    procedure btStopClick(ASender: TObject);
    procedure FormCreate(ASender: TObject);
    procedure btSwaggerUIClick(Sender: TObject);
  strict private
    procedure UpdateGUI;
    function ServerUrl: string;
  end;

var
  MainForm: TMainForm;

implementation

uses
  Sparkle.Utils;

{$R *.dfm}

resourcestring
  SServerStopped = 'Server stopped';
  SServerStartedAt = 'Server started at ';

{ TMainForm }

procedure TMainForm.btStartClick(ASender: TObject);
begin
  ServerContainer.SparkleHttpSysDispatcher.Start;
  UpdateGUI;
end;

procedure TMainForm.btStopClick(ASender: TObject);
begin
  ServerContainer.SparkleHttpSysDispatcher.Stop;
  UpdateGUI;
end;

procedure TMainForm.btSwaggerUIClick(Sender: TObject);
begin
  ShellExecute(Handle, 'open', PChar(TSparkleUtils.CombineUrlFast(ServerUrl, 'swaggerui')),
    nil, nil, SW_SHOWNORMAL);
end;

procedure TMainForm.FormCreate(ASender: TObject);
begin
  UpdateGUI;
end;

function TMainForm.ServerUrl: string;
const
  cHttp = 'http://+';
  cHttpLocalhost = 'http://localhost';
begin
  Result := StringReplace(ServerContainer.XDataServer.BaseUrl,
    cHttp, cHttpLocalhost, [rfIgnoreCase]);
end;

procedure TMainForm.UpdateGUI;
begin
  btStart.Enabled := not ServerContainer.SparkleHttpSysDispatcher.Active;
  btStop.Enabled := not btStart.Enabled;
  if ServerContainer.SparkleHttpSysDispatcher.Active then
    mmInfo.Lines.Add(SServerStartedAt + ServerUrl)
  else
    mmInfo.Lines.Add(SServerStopped);
end;

end.
