unit frmCardList;

{$mode Delphi}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, orca_scene2d, fgl, untData, untCard;

type

  { TFormCardList }

  TFormCardList = class(TForm)
    btnOK: TD2CornerButton;
    btnCancel: TD2CornerButton;
    btnAddCard: TD2CornerButton;
    D2Resources1: TD2Resources;
    Layout1: TD2Layout;
    lstCards: TD2ListBox;
    Root: TD2Background;
    Scene: TD2Scene;
    procedure btnAddCardClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FCardList: TFPGList<Int64>;
    procedure deleteCardItem(ACardId: Int64; AIndex: Integer);
  public
    procedure FillCardIds(list: TFPGList<Int64>);
  published
    property CardList: TFPGList<Int64> read FCardList;
  end;

var
  FormCardList: TFormCardList;

implementation

uses untListItem, frmSearchCard;

{$R *.lfm}

{ TFormCardList }

procedure TFormCardList.btnAddCardClick(Sender: TObject);
var
  cid: Int64 = 0;
  item: TCardListItemOp;
begin
  with TFormSearchCard.Create(Self) do begin
    if ShowModal = mrOK then begin
      cid := CardId;
    end;
    Free;
  end;
  if cid > 0 then begin
    FCardList.Add(cid);
    lstCards.BeginUpdate;
    item := TCardListItemOp.Create(lstCards);
    item.CardName:= Cards.GetCardName(cid);
    item.Id:= cid;
    item.ShowFace := False;
    item.OnDelete:= deleteCardItem;
    lstCards.EndUpdate;
  end;
end;

procedure TFormCardList.FormCreate(Sender: TObject);
begin
  FCardList := TFPGList<Int64>.Create;
end;

procedure TFormCardList.FormDestroy(Sender: TObject);
begin
  FCardList.Free;
end;

procedure TFormCardList.deleteCardItem(ACardId: Int64; AIndex: Integer);
var
  i: Integer;
begin
  // index matches
  if (FCardList[AIndex] = ACardId) then begin
    FCardList.Delete(AIndex);
    lstCards.Items[AIndex].Free;
    Exit;
  end;
  // index not match
  FCardList.Remove(ACardId);
  for i := 0 to lstCards.Count - 1 do begin
    if TCardListItemOp(lstCards.Items[i]).Id = ACardId then begin
      lstCards.Items[i].Free;
      Break;
    end;
  end;
end;

procedure TFormCardList.FillCardIds(list: TFPGList<Int64>);
var
  i: Integer;
  item: TCardListItemOp;
  cn: string;
begin
  FCardList.Clear;
  FCardList.AddList(list);
  lstCards.Clear;
  if (list.Count > 0) then begin
    lstCards.BeginUpdate;
    for i:= 0 to FCardList.Count - 1 do begin
      cn := Cards.GetCardName(FCardList[i]);
      item := TCardListItemOp.Create(lstCards);
      item.CardName:= cn;
      item.Id:= FCardList[i];
      item.ShowFace := False;
      item.OnDelete:= deleteCardItem;
    end;
    lstCards.EndUpdate;
  end;
end;

end.

