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, Vcl.ExtCtrls, System.IniFiles, ExeInfo, Common.Logging, Common.Config;

type
  TFMain = class(TForm)
    btnExit: TButton;
    initTimer: TTimer;
    memoInfo: TMemo;
    ExeInfo1: TExeInfo;

    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure initTimerTimer(Sender: TObject);
    procedure btnExitClick(Sender: TObject);
    procedure btnSwaggerUIClick(Sender: TObject);
  private
    procedure StartServers;
  end;

var
  FMain: TFMain;

implementation

uses
  Api.Server.Module, Sparkle.Utils, Api.Database, App.Server.Module, Api.Service, Api.ServiceImpl;

{$R *.dfm}

{ TFMain }

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

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


procedure TFMain.initTimerTimer(Sender: TObject);
begin
  initTimer.Enabled := False;

  Caption := Caption + ' ver ' + ExeInfo1.FileVersion;
  Logger.Log(1, 'Exe version: ' + ExeInfo1.FileVersion);

  try
    ServerConfig := TServerConfig.Create;
    LoadServerConfig;
    StartServers;
  except
    on E: Exception do
    begin
      Logger.Log(5, 'Failed to initialize server: ' + E.Message);
      memoInfo.Lines.Add('Failed to start server: ' + E.Message);
    end;
  end;
end;


procedure TFMain.StartServers;
var
  appServerUrl: string;
begin
  Logger.Log(1, '');
  Logger.Log(1, '******************************************************');
  Logger.Log(1, '              emWebsite XData Server                  ');
  Logger.Log(1, Format('              Version: %s                             ', [FMain.ExeInfo1.FileVersion]));
  Logger.Log(1, '                   by EM Systems, Inc.                ');
  Logger.Log(1, '******************************************************');
  Logger.Log(1, '');

  try
    ApiServerModule := TApiServerModule.Create(Self);
    ApiServerModule.StartApiServer(ServerConfig.url);

    Logger.Log(1, 'API Server started at: ' + ApiServerModule.XDataServer.BaseUrl);

    AppServerModule := TAppServerModule.Create(Self);
    AppServerModule.StartAppServer(ServerConfig.url);

    Logger.Log(1, 'App Server started at: ' + appServerUrl);

    Logger.Log(1, '');
  except
    on E: Exception do
    begin
      Logger.Log(5, 'Failed to start server modules: ' + E.Message);
      memoInfo.Lines.Add('Failed to start server modules: ' + E.Message);
    end;
  end;

  Logger.Log(1, '--- StartServers: Complete ---');
end;

procedure TFMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  ApiServerModule.Free;
  AppServerModule.Free;
  serverConfig.Free;
end;




end.

