unit ant_localizer;

//
//  Unit for generating localized texts.
//

{$MODE FPC}
{$MODESWITCH DEFAULTPARAMETERS}
{$MODESWITCH OUT}
{$MODESWITCH RESULT}

interface

uses
  {$IF Defined(WINDOWS)}ant_localizer_windows,{$ENDIF}
  dfiles,
  dfileiterator_nosysutils,
  deng, // for Log
  dansiview,
  ant_config;

function GetCurrentLang: TAnsiView;
procedure DetectDefaultLang;

procedure LoadTranslations;
      // Enumarates and load data/translation/*.lua files.
      // There should be at least en_US.lua as fallback language.

type
PLocalizer = ^TLocalizer;
TLocalizer = object
private
  FFileName: AnsiString;
  FLang: AnsiString; // culture name in format ll_CC
public
  procedure Init(const FileName: AnsiString);
      // Assignes the object to the FileName.
  procedure Done;
end;

implementation

var
  DefaultSystemLang: AnsiString;
  CurrentLang: AnsiString;
  Localizers: array of TLocalizer;

function GetCurrentLang: TAnsiView;
begin
  Exit(CurrentLang);
end;

procedure DetectDefaultLang;
begin
  DefaultSystemLang := {$IF Defined(WINDOWS)} GetLang_Windows {$ELSE} 'en_US' {$ENDIF};
  if Config.GetLang <> '' then begin
    CurrentLang := Config.GetLang;
  end else
    CurrentLang := DefaultSystemLang;
end;

procedure LoadTranslations;
const
  TRANSLATIONS_DIR = 'data/translation';
var
  It: TFileIterator;
  FullPath: AnsiString;
begin
  It.Init(TRANSLATIONS_DIR + '/*');
  while It.Next do begin
    FullPath := TRANSLATIONS_DIR + '/' + It.FileName;
    if FileExists(FullPath) then begin
      SetLength(Localizers, Length(Localizers) + 1);
      Localizers[High(Localizers)].Init(FullPath);
    end;
  end;
  It.Done;
end;

procedure TLocalizer.Init(const FileName: AnsiString);
var
  I: Int32;
begin
  FFileName := FileName;
  FLang := FFileName;

  I := Length(FLang);
  while I > 0 do begin
    if FLang[I] = '.' then begin
      FLang := Copy(FLang, 1, I);
      break;
    end;
    Dec(I);
  end;

  I := Length(FLang);
  while I > 0 do begin
    if (FLang[I] = '/') or (FLang[I] = '\') then begin
      FLang := Copy(FLang, I + 1, Length(FLang) - I - 1);
      break;
    end;
    Dec(I);
  end;

  // TODO load
  Log('Found translation ' + FLang + ' in ' + FileName);
end;

procedure TLocalizer.Done;
begin
end;

end.
