unit mod1;

interface

uses
  Classes, SyncObjs, WebBroker, HTTPApp, HTTPProd;

type
  TFoo = class(TWebModule)
    Home: TPageProducer;
    procedure WebModuleCreate(Sender: TObject);
    procedure WebModuleDestroy(Sender: TObject);
  private
    FCriticalSection: TCriticalSection;
  end;

var
  Foo: TFoo;

implementation

{$R *.dfm}

uses
  Windows, SysUtils, Rubies, uAppInit, Pythia, WebExtension;

const
  LogFile = 'logs\apollo.log';

procedure Stdout(S: string);
var
  F: TextFile;
begin
  AssignFile(F, LogFile);
  if FileExists(LogFile) then Append(F) else Rewrite(F);
  Write(F, S);
  Flush(F);
  CloseFile(F);
end;

procedure NewLogFile;
var
  F: TextFile;
begin
  AssignFile(F, LogFile);
  ForceDirectories(ExtractFileDir(ExpandFileName(LogFile)));
  Rewrite(F);
  CloseFile(F);
end;

procedure TFoo.WebModuleCreate(Sender: TObject);
var
  vWebApp, vWebMod: Tvalue;
begin
  FCriticalSection := TCriticalSection.Create;
  FCriticalSection.Enter;
  try
    NewLogFile;
//    Stdout('create'+NL);
    PhiAppInit;
    PhiSetStdoutProc(Stdout);
    rb_require(PChar('phi'));
    rb_require(PChar('web'));
    vWebApp := Regist_WebApplication(TWebApplication(Sender));
    vWebMod := Regist_WebModule(Self, vWebApp);
    Regist_PageProducer(Home, vWebMod);
    PhiLoadProtect(PChar('web_init.rb'), nil);
  finally
    FCriticalSection.Leave;
  end;
end;

procedure TFoo.WebModuleDestroy(Sender: TObject);
begin
  FCriticalSection.Enter;
  try
    ruby_finalize;
//    Stdout('destroy'+NL);
  finally
    FCriticalSection.Leave;
  end;
end;

end.
