unit untConfig;

{$mode ObjFPC}{$H+}

interface

uses
  Classes, SysUtils, Registry;

type

  { TConfigReader }

  TConfigReader = class
  public
    class function GetMCToken(): string;
    class procedure SaveMCToken(AToken: string);
    class function GetMDPro3InstallPath(): string;
  end;

implementation

{ TConfigReader }

class function TConfigReader.GetMCToken(): string;
var
  ACfgPath: String;
  i: Integer;
  AToken: String = '';
begin
  ACfgPath:= GetMDPro3InstallPath() + DirectorySeparator + 'Data' + DirectorySeparator + 'config.conf';
  with TStringList.Create do begin
    LoadFromFile(ACfgPath);
    // MyCardToken->
    for i := 0 to Count - 1 do begin
      if Strings[i].StartsWith('MyCardToken->') then begin
        // read token
        AToken := Strings[i].Replace('MyCardToken->', '', [rfIgnoreCase, rfReplaceAll]);
      end;
    end;
    Free;
  end;
  Exit(AToken);
end;

class procedure TConfigReader.SaveMCToken(AToken: string);
var
  ACfgPath: String;
  AFound: Boolean = False;
  i: Integer;
begin
  ACfgPath:= GetMDPro3InstallPath() + DirectorySeparator + 'Data' + DirectorySeparator + 'config.conf';
  with TStringList.Create do begin
    LoadFromFile(ACfgPath);
    for i := 0 to Count - 1 do begin
      if Strings[i].StartsWith('MyCardToken->') then begin
        AFound := True;
        // override token
        Strings[i] := 'MyCardToken->' + AToken;
      end;
    end;
    if (not AFound) then begin
      Add('MyCardToken->' + AToken);
    end;
    SaveToFile(ACfgPath);
    Free;
  end;

end;

class function TConfigReader.GetMDPro3InstallPath(): string;
var
  AOpened: Boolean;
  APath: string = '';
begin
  // GetMDPro3InstallPath
  with TRegistry.Create do begin
    RootKey:= HKEY_CURRENT_USER;
    AOpened := OpenKey('Software\MDPro3\MDPro3Install', False);
    if AOpened then begin
      APath := ReadString('InstallPath');
      CloseKey;
    end;
    Free;
  end;
  Exit(APath);
end;

end.

