unit Forms.Game;

interface
uses
  System.Classes,
  Vcl.Controls,
  Vcl.Dialogs,
  Vcl.ExtCtrls,
  Vcl.Forms,
  Vcl.Mask,
  Vcl.StdCtrls,

  JvExMask,
  JvToolEdit,

  Game.Base;


type
  TGameForm = class(TForm)
    btnCancel: TButton;
    btnOK: TButton;
    cmbGame: TComboBox;
    deLocation: TJvDirectoryEdit;
    gbGame: TGroupBox;
    lblGame: TLabel;
    lblLocation: TLabel;
    pnlButtons: TPanel;

    procedure FormCreate(Sender: TObject);
    procedure btnOKClick(Sender: TObject);
  private
    function GetGameClass: TCustomGameClass;
    function GetLocation: string;
    procedure SetGameClass(const Value: TCustomGameClass);
    procedure SetLocation(const Value: string);
  protected
    property GameClass: TCustomGameClass read GetGameClass write SetGameClass;
    property Location: string read GetLocation write SetLocation;
  public
    class function Insert(AOwner: TComponent; out AGame: TCustomGame): Boolean;
  end;


implementation
uses
  System.SysUtils,
  Winapi.Windows,

  Game.Registry;


{$R *.dfm}


{ TGameForm }
class function TGameForm.Insert(AOwner: TComponent; out AGame: TCustomGame): Boolean;
begin
  with Self.Create(AOwner) do
  try
    Result := (ShowModal = mrOk);
    if Result then
      AGame := GameClass.Create(Location);
  finally
    Free;
  end;
end;


procedure TGameForm.FormCreate(Sender: TObject);
var
  gameClass: TCustomGameClass;

begin
  cmbGame.Items.BeginUpdate;
  try
    cmbGame.Items.Clear;

    for gameClass in TGameRegistry.RegisteredGames do
      cmbGame.Items.AddObject(gameClass.GameName, TObject(gameClass));
  finally
    cmbGame.Items.EndUpdate;
    cmbGame.ItemIndex := 0;
  end;
end;


procedure TGameForm.btnOKClick(Sender: TObject);
begin
  if not Assigned(GameClass) then
  begin
    MessageBox(Self.Handle, 'Please select the game type', 'Error', MB_OK or MB_ICONERROR);
    ActiveControl := cmbGame;
    exit;
  end;

  if (Length(Location) = 0) or (not DirectoryExists(Location)) then
  begin
    MessageBox(Self.Handle, 'Please enter a valid location', 'Error', MB_OK or MB_ICONERROR);
    ActiveControl := deLocation;
    exit;
  end;

  ModalResult := mrOk;
end;


function TGameForm.GetGameClass: TCustomGameClass;
begin
  Result := nil;
  if cmbGame.ItemIndex > -1 then
    Result := TCustomGameClass(cmbGame.Items.Objects[cmbGame.ItemIndex]);
end;


function TGameForm.GetLocation: string;
begin
  Result := deLocation.Text;
end;


procedure TGameForm.SetGameClass(const Value: TCustomGameClass);
begin
  cmbGame.ItemIndex := cmbGame.Items.IndexOfObject(TObject(Value));
end;


procedure TGameForm.SetLocation(const Value: string);
begin
  deLocation.Text := Value;
end;

end.
