program SQLiteConsoleServer;

{$APPTYPE CONSOLE}

uses
  System.SysUtils, System.Generics.Collections,
  Aurelius.Drivers.Interfaces,
  Aurelius.Drivers.SQLite,
  Aurelius.Sql.SQLite,
  Aurelius.Schema.SQLite,
  Sparkle.HttpSys.Server,
  XData.Aurelius.ConnectionPool,
  XData.Server.Module,
  AureliusEntities in '..\common\AureliusEntities.pas',
  DatabaseUtils in '..\common\DatabaseUtils.pas',
  Server.Module in 'Server.Module.pas' {ServerModule: TDataModule};

const
  DefaultServerUrl = 'http://localhost:2001/tms/music';

var
  Servers: TDictionary<string, TServerModule>;

procedure StartServer;
var
  ServerModule: TServerModule;
  I: Integer;
begin
  Servers := TObjectDictionary<string, TServerModule>.Create([doOwnsValues]);
  try
    // Create one module for each URL passed in command-line. For example, the following
    // command-line will start a server that listen on both http and https urls
    // SQLiteConsoleServer.exe http://+:80/tms/music https://+:443/tms/music
    if ParamCount > 0 then
    begin
      for I := 1 to ParamCount do
      begin
        if Servers.ContainsKey(ParamStr(I)) then
          Continue;
        ServerModule := TServerModule.Create(nil);
        ServerModule.StartServer(ParamStr(I));
        Servers.Add(ParamStr(I), ServerModule);
      end;
    end
    else
    begin
      // If not command-line parameters are specific, use default URL
      ServerModule := TServerModule.Create(nil);
      ServerModule.StartServer(DefaultServerUrl);
      Servers.Add(DefaultServerUrl, ServerModule);
    end;

    WriteLn('Server started. Press ENTER to stop.');
    ReadLn;
  finally
    FreeAndNil(Servers);
  end;
end;

begin
  ReportMemoryLeaksOnShutdown := true;
  try
    StartServer;
  except
    on e: exception do
    begin
      WriteLn(e.Message);
      ReadLn;
    end;
  end;
end.

