unit Persist.GameList;

interface
uses
  Game.List;


type
  TGameListPersist = class(TObject)
  public
    class procedure Load(const AFileName: string; AList: TGameList);
    class procedure Save(const AFileName: string; AList: TGameList);
  end;


implementation
uses
  System.IOUtils,
  System.SysUtils,

  superobject,

  Game.Base,
  Game.Registry;


const
  KeyClassName = 'className';
  KeyLocation = 'location';


{ TGameListPersist }
class procedure TGameListPersist.Load(const AFileName: string; AList: TGameList);
var
  inputList: ISuperObject;
  inputGame: ISuperObject;
  gameClass: TCustomGameClass;

begin
  if not FileExists(AFileName) then
    exit;

  inputList := SO(TFile.ReadAllText(AFileName));
  if Assigned(inputList) then
  begin
    for inputGame in inputList do
    begin
      gameClass := TGameRegistry.ByClassName(inputGame.S[KeyClassName]);
      if Assigned(gameClass) then
        AList.Add(gameClass.Create(inputGame.S[KeyLocation]));
    end;
  end;
end;


class procedure TGameListPersist.Save(const AFileName: string; AList: TGameList);
var
  outputList: ISuperObject;
  outputGame: ISuperObject;
  game: TCustomGame;

begin
  outputList := SA([]);

  for game in AList do
  begin
    outputGame := SO();
    outputGame.S[KeyClassName] := game.ClassName;
    outputGame.S[KeyLocation] := game.Location;
//    outputGame.B['active'] := True;

    outputList.AsArray.Add(outputGame);
  end;

  if ForceDirectories(ExtractFilePath(AFileName)) then
    TFile.WriteAllText(AFileName, outputList.AsJSon(True));
end;

end.
