program emT3XDataServer;

uses
  FastMM4,
  System.SyncObjs,
  System.SysUtils,
  Vcl.StdCtrls,
  IniFiles,
  Vcl.Forms,
  Vcl.Dialogs,
  Api.Server.Module in 'Source\Api.Server.Module.pas' {ApiServerModule: TDataModule},
  Main in 'Source\Main.pas' {FMain},
  Common.Logging in 'Source\Common.Logging.pas',
  Api.Database in 'Source\Api.Database.pas' {ApiDatabase: TDataModule},
  Common.Middleware.Logging in 'Source\Common.Middleware.Logging.pas',
  Common.Config in 'Source\Common.Config.pas',
  Auth.Server.Module in 'Source\Auth.Server.Module.pas' {AuthServerModule: TDataModule},
  Auth.Database in 'Source\Auth.Database.pas' {AuthDatabase: TDataModule},
  uLibrary in 'Source\uLibrary.pas',
  Auth.Service in 'Source\Auth.Service.pas',
  Auth.ServiceImpl in 'Source\Auth.ServiceImpl.pas',
  App.Server.Module in 'Source\App.Server.Module.pas' {AppServerModule: TDataModule},
  Api.Service in 'Source\Api.Service.pas',
  Api.ServiceImpl in 'Source\Api.ServiceImpl.pas',
  Common.Ini in 'Source\Common.Ini.pas';

type
  TMemoLogAppender = class( TInterfacedObject, ILogAppender )
  private
    FLogLevel: Integer;
    FLogMemo: TMemo;
    FCriticalSection: TCriticalSection;
  public
    constructor Create(ALogLevel: Integer; ALogMemo: TMemo);
    destructor Destroy; override;
    procedure Send(logLevel: Integer; Log: ILog);
  end;

  TFileLogAppender = class( TInterfacedObject, ILogAppender )
  private
    FLogLevel: Integer;
    FLogFile: string;
    FCriticalSection: TCriticalSection;
  public
    constructor Create(ALogLevel: Integer; AFilename: string; AFileNum: Integer);
    destructor Destroy; override;
    procedure Send(logLevel: Integer; Log: ILog);
  end;

{ TMemoLogAppender }
constructor TMemoLogAppender.Create(ALogLevel: Integer; ALogMemo: TMemo);
begin
  FLogLevel := ALogLevel;
  FLogMemo := ALogMemo;
  FCriticalSection := TCriticalSection.Create;
end;

destructor TMemoLogAppender.Destroy;
begin
  FCriticalSection.Free;
  inherited;
end;

procedure TMemoLogAppender.Send(logLevel: Integer; Log: ILog);
var
  FormattedMessage: string;
  LogTime: TDateTime;
  LogMsg: string;

begin
  FCriticalSection.Acquire;
  try
    LogTime := Now;

    FormattedMessage := FormatDateTime('[yyyy-mm-dd HH:nn:ss.zzz]', LogTime);
    LogMsg := Log.GetMessage;
    if LogMsg.IsEmpty then
      FormattedMessage := ''
    else
      FormattedMessage := FormattedMessage + '[' + IntToStr(logLevel) +'] ' + LogMsg;

    if logLevel <= FLogLevel then
      FLogMemo.Lines.Add( FormattedMessage );
  finally
    FCriticalSection.Release;
  end;
end;

{ TFileLogAppender }
constructor TFileLogAppender.Create(ALogLevel: integer; AFilename: string; AFileNum: integer);
var
  iniFile: TIniFile;
  logsDir: string;
begin
  FLogLevel := ALogLevel;
  FCriticalSection := TCriticalSection.Create;
  logsDir := ExtractFilePath(Application.ExeName) + 'logs\';
  if not DirectoryExists(logsDir) then
    CreateDir(logsDir);

  FLogFile := logsDir + AFilename + Format( '%.4d', [AFileNum] ) + '.log';
end;

destructor TFileLogAppender.Destroy;
begin
  FCriticalSection.Free;
  inherited;
end;

procedure TFileLogAppender.Send(logLevel: integer; Log: ILog);
var
  formattedMessage: string;
  logTime: TDateTime;
  logMsg: string;
  txtFile: TextFile;

begin
  FCriticalSection.Acquire;
  try
    logTime := Now;

    formattedMessage := FormatDateTime('[yyyy-mm-dd HH:nn:ss.zzz]', logTime);
    logMsg := Log.GetMessage;
    if logMsg.IsEmpty then
      formattedMessage := ''
    else
      formattedMessage := formattedMessage + '[' + IntToStr(logLevel) +'] ' + logMsg;

    try
      AssignFile( txtFile, FLogFile );
      if FileExists(FLogFile) then
        Append( txtFile )
      else
        ReWrite( txtFile );
      if logLevel <= FLogLevel then
        WriteLn( txtFile, formattedMessage );
    finally
      CloseFile(txtFile);
    end;
  finally
    FCriticalSection.Release;
  end;
end;

{$R *.res}

var
  iniFilename: string;
  iniFile: TIniFile;
  //memoLogLevel: Integer;
  //fileLogLevel: Integer;
  //fileNum: Integer;
  iniStr: string;
begin
  ReportMemoryLeaksOnShutdown := True;

  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TFMain, FMain);
  iniFilename := ChangeFileExt( Application.ExeName, '.ini' );
  iniFile := TIniFile.Create( iniFilename );
  try

//    LoadIniEntries;
    //memoLogLevel := iniFile.ReadInteger('Settings', 'MemoLogLevel', 3);
    //fileLogLevel := iniFile.ReadInteger('Settings', 'FileLogLevel', 4);
    //fileNum := iniFile.ReadInteger( 'Settings', 'LogFileNum', 0 );

    Logger.AddAppender( TMemoLogAppender.Create(iniEntries.memoLogLevel, FMain.memoinfo) );
    Logger.AddAppender( TFileLogAppender.Create(iniEntries.fileLogLevel, 'emT3XDataServer', iniEntries.logFileNum) );

    Logger.Log( 1, '*******************************************************' );
    Logger.Log( 1, '*                  emT3XDataServer                    *' );
    Logger.Log( 1, Format('*                 Version: %s                    *', [FMain.ExeInfo1.FileVersion]));
    Logger.Log( 1, '*            Developed by EM Systems, Inc.            *' );
    Logger.Log( 1, '*******************************************************' );
    Logger.Log( 1, '' );

    LoadIniEntries;
    Logger.Log( 1, 'iniFile: ' + iniFilename );

    iniStr := iniFile.ReadString( 'Settings', 'MemoLogLevel', '' );
    if iniStr.IsEmpty then
      Logger.Log( 1, '--Settings->MemoLogLevel: ini entry not found - default: ' + IntToStr(iniEntries.memoLogLevel) )
    else
      Logger.Log( 1, '--Settings->MemoLogLevel: ini entry: ' + iniStr );

    iniStr := iniFile.ReadString( 'Settings', 'FileLogLevel', '' );
    if iniStr.IsEmpty then
      Logger.Log( 1, '--Settings->FileLogLevel: ini entry not found - default: ' + IntToStr(iniEntries.fileLogLevel) )
    else
      Logger.Log( 1, '--Settings->FileLogLevel: ini entry: ' + iniStr );

    Logger.Log( 1, '' );
    iniStr := iniFile.ReadString( 'Settings', 'LogFileNum', '' );
    if iniStr = '1' then
      Logger.Log( 1, '--Settings->LogFileNum: ini entry not found - LogFileNum 1 added to iniFile' )
    else
      Logger.Log( 1, '--Settings->LogFileNum: ini entry: ' + iniStr );
  finally
    iniFile.Free;
  end;

  Application.Run;
end.

