unit WebModuleUnit1;

interface

uses
  System.SysUtils, System.Classes, Web.HTTPApp, System.IOUtils,
  Sparkle.WebBroker.Server,
  Sparkle.WebBroker.Adapter,
  Sparkle.HttpServer.Module,
  Sparkle.HttpServer.Context, XData.Server.Module, Aurelius.Drivers.Interfaces,
  Aurelius.Drivers.SQLite, Aurelius.Comp.Connection, XData.Comp.ConnectionPool,
  Sparkle.Comp.Server, XData.Comp.Server, Aurelius.Engine.DatabaseManager,
  Aurelius.Comp.DBSchema;

type
  TWebModule1 = class(TWebModule)
    XDataServer1: TXDataServer;
    XDataConnectionPool1: TXDataConnectionPool;
    AureliusConnection1: TAureliusConnection;
    AureliusDBSchema1: TAureliusDBSchema;
    procedure WebModule1DefaultHandlerAction(Sender: TObject;
      Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
    procedure WebModuleCreate(Sender: TObject);
    procedure WebModuleDestroy(Sender: TObject);
  private
    Server: TWebBrokerServer;
    procedure PrepareDatabase;
  public
  end;

var
  WebModuleClass: TComponentClass = TWebModule1;

implementation

uses
  AureliusEntities,
  DatabaseUtils;

{%CLASSGROUP 'System.Classes.TPersistent'}

{$R *.dfm}

procedure TWebModule1.PrepareDatabase;
var
  DBFileName: string;
begin
  DBFileName := TPath.Combine(TPath.GetTempPath, 'music.db');
  AureliusConnection1.Params.Values['Database'] := DBFileName;
  if not TFile.Exists(DBFileName) then
  begin
    AureliusDBSchema1.UpdateDatabase;
    AureliusDBSchema1.ReleaseDBManager;
    DatabaseUtils.UpdateDatabase(XDataConnectionPool1.GetPoolInterface.GetConnection);
  end;
end;

procedure TWebModule1.WebModule1DefaultHandlerAction(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
  Adapter: IWebBrokerAdapter;
begin
  Adapter := TWebBrokerAdapter.Create(Request, Response);
  Server.DispatchRequest(Adapter);
end;

procedure TWebModule1.WebModuleCreate(Sender: TObject);
begin
  PrepareDatabase;
  Server := TWebBrokerServer.Create;
  Server.Dispatcher.AddModule(XDataServer1.CreateModule);
end;

procedure TWebModule1.WebModuleDestroy(Sender: TObject);
begin
  Server.Free;
end;

end.
