unit fMain;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Generics.Collections, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CustomerService,
  Data.DB, Aurelius.Bind.BaseDataset, Aurelius.Bind.Dataset, XData.Client,
  Vcl.ExtCtrls, Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids;

type
  TForm5 = class(TForm)
    AureliusDataset1: TAureliusDataset;
    DBGrid1: TDBGrid;
    DBNavigator1: TDBNavigator;
    DataSource1: TDataSource;
    AureliusDataset1Id: TIntegerField;
    AureliusDataset1Name: TStringField;
    AureliusDataset1Country: TStringField;
    procedure FormDestroy(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure AureliusDataset1ObjectInsert(Dataset: TDataSet; AObject: TObject);
    procedure AureliusDataset1ObjectRemove(Dataset: TDataSet; AObject: TObject);
    procedure AureliusDataset1ObjectUpdate(Dataset: TDataSet; AObject: TObject);
  strict private
    Customers: TList<TCustomer>;
    ToDestroy: TList<TObject>;
    Client: TXDataClient;
    Service: ICustomerService;
  public
    procedure LoadData;
  end;

var
  Form5: TForm5;

implementation

{$R *.dfm}

procedure TForm5.AureliusDataset1ObjectInsert(Dataset: TDataSet;
  AObject: TObject);
begin
  Service.CreateCustomer(AObject as TCustomer);
  ToDestroy.Add(AObject);
end;

procedure TForm5.AureliusDataset1ObjectRemove(Dataset: TDataSet;
  AObject: TObject);
begin
  Service.DeleteCustomer((AObject as TCustomer).Id);
end;

procedure TForm5.AureliusDataset1ObjectUpdate(Dataset: TDataSet;
  AObject: TObject);
var
  Customer: TCustomer;
begin
  Customer := AObject as TCustomer;
  Service.UpdateCustomer(Customer.Id, Customer);
end;

procedure TForm5.FormCreate(Sender: TObject);
begin
  ReportMemoryLeaksOnShutdown := True;
  Client := TXDataClient.Create;
  Client.Uri := 'http://localhost:2001/tms/firedacsql';
  ToDestroy := TObjectList<TObject>.Create;
  Service := Client.Service<ICustomerService>;
  LoadData;
end;

procedure TForm5.FormDestroy(Sender: TObject);
begin
  AureliusDataset1.Close;
  Customers.Free;
  Client.Free;
  ToDestroy.Free;
end;

procedure TForm5.LoadData;
begin
  FreeAndNil(Customers);
  Customers := Service.GetCustomers;
  AureliusDataset1.Close;
  AureliusDataset1.SetSourceList(Customers);
  AureliusDataset1.Open;
end;

end.
