unit Main;

interface

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

type
  TFMain = class(TForm)
    memoInfo: TMemo;
    btStart: TButton;
    btStop: TButton;
    btnSwaggerUI: TButton;
    btnData: TButton;
    btnExit: TButton;
    Timer1: TTimer;
    procedure btStartClick(ASender: TObject);
    procedure btStopClick(ASender: TObject);
    procedure FormCreate(ASender: TObject);
    procedure btnSwaggerUIClick(Sender: TObject);
    procedure btnDataClick(Sender: TObject);
    procedure btnExitClick(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure ContactFormData(AText: String);
  strict private
    procedure UpdateGUI;
    function ServerUrl: string;
  end;

var
  FMain: TFMain;

implementation

uses
  Common.Logging,
  Sparkle.Utils,
  Data;



{$R *.dfm}

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

{ TMainForm }

procedure TFMain.ContactFormData(AText: String);
begin
  if memoInfo.CanFocus then
    TThread.Queue(nil, procedure
    begin
      memoInfo.Lines.Add(AText);
    end)
  else
    TThread.Synchronize(nil, procedure
    begin
      memoInfo.Lines.Add(AText);
    end);
end;

procedure TFMain.btnDataClick(Sender: TObject);
begin
  FData := TFData.Create( self );
  FData.ShowModal;
  FData.Free;
end;

procedure TFMain.btnExitClick(Sender: TObject);
begin
  Close;
end;

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

procedure TFMain.btStartClick(ASender: TObject);
begin
  FServerContainer.SparkleHttpSysDispatcher.Start;
  UpdateGUI;
end;

procedure TFMain.btStopClick(ASender: TObject);
begin
  FServerContainer.SparkleHttpSysDispatcher.Stop;
  UpdateGUI;
end;

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

procedure TFMain.Timer1Timer(Sender: TObject);
begin
  Timer1.Enabled := False;
  Logger.Log( 3, 'Timer1Timer event' );
  UpdateGUI;
end;

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

procedure TFMain.UpdateGUI;
const
  cHttp = 'http://+';
  cHttpLocalhost = 'http://localhost';
begin
  btStart.Enabled := not FServerContainer.SparkleHttpSysDispatcher.Active;
  btStop.Enabled := not btStart.Enabled;
  if FServerContainer.SparkleHttpSysDispatcher.Active then
    memoInfo.Lines.Add(SServerStartedAt + StringReplace(
      FServerContainer.XDataServer.BaseUrl,
      cHttp, cHttpLocalhost, [rfIgnoreCase]))
  else
    memoInfo.Lines.Add(SServerStopped);
end;

end.
