unit Unit_commune;

{$mode objfpc}{$H+}

interface

uses
   Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls, Buttons, Spin,ColorBox, LResources,LCLType,
   {$ifdef windows}windows,shellapi,registry,{$endif}  Menus,LazHelpHTML,UTF8Process,
  ComCtrls,clipbrd,printers, FileUtil,LCLIntf,Translations,gettext;

var
    repertoire_executable,repertoire_exemples,repertoire_aide,nomexecutable,repertoire_config_perso,
    repertoire_simul_perso,chemin_po:string;
    nom_fichier_config_optgeo,
    nom_fichier_config_perso,
   repertoire_actuel,
     repertoire_exemples_par_defaut,repertoire_simul_perso_par_defaut:string;
         nom_ini_file:string;
          Lang, FallbackLang, ID_lang: String;  liste_langues:tstringlist;
          PODirectory: String;
      f_ini:textfile;
      Search:sysutils.TSearchRec;
    Function MyGetAppConfigDirUTF8: String;
    {$ifdef windows}
Function MyGetMesDocumentsUTF8: String; {$endif}
  Function ExpandEnvironmentString(s: String): String;

implementation

  label 1888;

Function ExpandEnvironmentString(s: String): String;
    Var i, k: Integer;
        sl: TStringList;
        s2: String;
        bP, bD: Boolean;
    Begin
      Result := s;
      bP := Pos('%', s) > 0;
      bD := Pos('$', s) > 0;
      If Not(bP Or bD) Then Exit; // Nichts zu konvertieren
      sl := TStringList.Create;
      sl.Sorted := bD;
      For i := GetEnvironmentVariableCount - 1 DownTo 0 Do // Alle Variablen in eine Liste merken
      Begin
        s2 := GetEnvironmentStringUTF8(i);
        If Length(s2) >= 2 Then
          If s2[1] <> '=' Then // Bei Windows kommt sowas auch vor, daher wegoptimieren
            sl.Add(s2);
      end;

      k := 0;
      Repeat // Durchlaufe so oft bis alle Env-Variablen aufgelöst sind
        s2 := Result;
        For i := sl.Count - 1 DownTo 0 Do
        Begin
          If bP Then
          Begin
            Result := StringReplace(Result, '%' + sl.Names[i] + '%', sl.ValueFromIndex[i], [rfReplaceAll, rfIgnoreCase]);
            If Pos('%', Result) = 0 Then bP := False;
          end;
          If bD Then
          Begin
            Result := StringReplace(Result, '$' + sl.Names[i], sl.ValueFromIndex[i], [rfReplaceAll]);
            If Pos('$', Result) = 0 Then bD := False;
          end;
          If Not(bP Or bD) Then Break;
        end;
        If Not(bP Or bD) Then Break;
        If SameText(s2, Result) Then Break; // % $ nicht konvertierbar, da im System nicht vorhanden
        Inc(k);
        If k > sl.Count - 2 Then Break; // Max Durchläufe
      Until True;
      sl.Free;
    end;



 Function MyGetAppConfigDirUTF8: String;
{il est necessaire de modifier GetAppConfigDir car sur les systemes
windows renvoie local setting\application data au lieu de application data}
var
  I: Integer;
  EnvVars: TStringList;
begin
{$ifndef windows}
result:=systoutf8(SysUtils.GetAppConfigDir(false));
{$endif}
 {$ifdef windows}
  EnvVars := TStringList.Create;
try
       for I := 0 to GetEnvironmentVariableCount - 1 do
      EnvVars.Add(GetEnvironmentString(I));
        result:=systoutf8(AppendPathDelim(EnvVars.Values['APPDATA'])+'optgeo\');

  finally
    EnvVars.Free;
  end;
  {$endif}
 end;


 {$ifdef windows}
Function MyGetMesDocumentsUTF8: String;
var
    Reg: TRegistry;

begin

  Reg := TRegistry.Create;
  try
    Reg.RootKey := HKEY_CURRENT_USER;
    Reg.OpenKey('Software\Microsoft\Windows\CurrentVersion\'
      + 'Explorer\User Shell Folders\', False);
    result:=ExpandEnvironmentString(Reg.ReadString('Personal'));
  finally
    Reg.Free;

  end;
    end;
    {$endif}

 initialization

  repertoire_executable:=AppendPathDelim(extractfilepath(systoutf8(Application.ExeName)));
           nomexecutable:=extractfilename(Application.ExeName);

         repertoire_aide:=AppendPathDelim(repertoire_executable+'aide');
          repertoire_config_perso:=AppendPathDelim(MyGetAppConfigDirUTF8);

          {$ifdef windows}
  repertoire_simul_perso:=AppendPathDelim(AppendPathDelim(MyGetMesDocumentsUTF8)+'MesSimulations');
   {$endif}
   {$ifndef windows}
    repertoire_simul_perso:=AppendPathDelim({repertoire_config_perso}GetUserDir+'MesSimulations');
     {$endif}

     nom_fichier_config_optgeo:=repertoire_config_perso+'optgeo.cfg';

    nom_fichier_config_perso:=repertoire_config_perso+'perso.cfg';
    nom_ini_file:=repertoire_config_perso+'optgeo.ini';

     repertoire_simul_perso_par_defaut:=repertoire_simul_perso;
        repertoire_exemples:=AppendPathDelim(repertoire_executable+'exemples');
     repertoire_exemples_par_defaut:=repertoire_exemples;
    repertoire_actuel:=repertoire_exemples;

      liste_langues:=tstringlist.create;


        chemin_po:=AppendPathDelim(repertoire_executable+'lang');


        If FindFirstutf8(Chemin_po+'optgeo.*.po',faAnyFile,Search)=0
 Then Begin
   Repeat
      if (Search.Name='.') or (Search.Name='..') or (Search.Name='')
        then continue;
              { liste_langues.Add(copy(Search.name,length(Search.name)-4,2)); }
              ID_lang:=copy(Search.name,length('optgeo.')+1,
                 length(Search.Name)-length('optgeo..po'));
              if (ID_lang<>'') and (Pos('.',ID_lang)<1) and (liste_langues.IndexOf(ID_lang)<0)
      then liste_langues.Add(ID_lang);
              Until FindNextutf8(Search)<>0;
   FindCloseutf8(Search);
 End;






lang:='';  FallbackLang:='';



     if not(fileexistsutf8(nom_ini_file)) then begin
       GetLanguageIDs(lang,FallbackLang);
             if ((liste_langues.indexof(uppercase(lang))=-1) and
            (liste_langues.indexof(uppercase(FallbackLang))=-1)) then
          begin
        Lang:='fr_FR';  FallbackLang:='fr';
               end;
       goto 1888;
       end;



       assignfile(f_ini,UTF8ToSys(nom_ini_file));
       reset(f_ini);
       readln(f_ini,lang);
              readln(f_ini,FallbackLang);
       closefile(f_ini);






     1888:
PODirectory:=IncludeTrailingPathDelimiter(
                        IncludeTrailingPathDelimiter(
                         ExtractFilePath(Application.ExeName))+'lang');
     Translations.TranslateUnitResourceStrings('LCLStrConsts', PODirectory + 'lclstrconsts.%s.po', Lang, FallbackLang);
     Translations.TranslateUnitResourceStrings('UChaines', PODirectory + 'optgeo.%s.po', Lang, FallbackLang);


end.

