program kgOrdersServer;

uses
  FastMM4,
  System.SyncObjs,
  System.SysUtils,
  Vcl.StdCtrls,
  IniFiles,
  Vcl.Forms,
  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',
  Lookup.Service in 'Source\Lookup.Service.pas',
  Auth.ServiceImpl in 'Source\Auth.ServiceImpl.pas',
  Lookup.ServiceImpl in 'Source\Lookup.ServiceImpl.pas',
  App.Server.Module in 'Source\App.Server.Module.pas' {AppServerModule: TDataModule},
  Data in 'Source\Data.pas' {FData},
  rOrderList in 'Source\rOrderList.pas' {rptOrderList: TDataModule},
  rOrderCorrugated in 'Source\rOrderCorrugated.pas' {rptOrderCorrugated: TDataModule},
  rOrderWeb in 'Source\rOrderWeb.pas' {rptOrderWeb: TDataModule},
  rOrderCutting in 'Source\rOrderCutting.pas' {rptOrderCutting: TDataModule},
  qbAPI in 'Source\qbAPI.pas' {fQB};

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);
    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);
var
  iniFile: TIniFile;
  fileNum: integer;
  logsDir: string;
begin
  FLogLevel := ALogLevel;
  FCriticalSection := TCriticalSection.Create;
  logsDir := ExtractFilePath(Application.ExeName) + 'logs\';
  if not DirectoryExists(logsDir) then
    CreateDir(logsDir);

  iniFile := TIniFile.Create( ExtractFilePath(Application.ExeName) + 'kgOrdersServer.ini' );
  try
    fileNum := iniFile.ReadInteger( 'Settings', 'LogFileNum', 0 );
    FLogFile := logsDir + AFilename + Format( '%.4d', [fileNum] ) + '.log';
    iniFile.WriteInteger( 'Settings', 'LogFileNum', fileNum + 1 );
  finally
    iniFile.Free;
  end;
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
  iniFile: TIniFile;
  MemoLogLevel: Integer;
  FileLogLevel: Integer;

begin
  ReportMemoryLeaksOnShutdown := True;
  Application.Initialize;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TFMain, FMain);
  iniFile := TIniFile.Create( ExtractFilePath(Application.ExeName) + 'kgOrdersServer.ini' );
  try
    MemoLogLevel := iniFile.ReadInteger( 'Settings', 'MemoLogLevel', 3 );
    FileLogLevel := iniFile.ReadInteger( 'Settings', 'FileLogLevel', 4 );
  finally
    iniFile.Free;
  end;
  Logger.AddAppender(TMemoLogAppender.Create( MemoLogLevel, FMain.memoinfo ));
  Logger.AddAppender(TFileLogAppender.Create( FileLogLevel, 'kgOrdersServer' ));
  Application.Run;
end.
