unit View.TasksDataGrid;

interface

uses
  System.SysUtils, System.Classes,
  JS, Web, WEBLib.Forms, WEBLib.Dialogs, WEBLib.StdCtrls,
  XData.Web.Client,
  WEBLib.DataGrid,
  Utils, WEBLib.DataGrid.Common, Vcl.StdCtrls, Vcl.Controls, Vcl.Grids,
  WEBLib.DataGrid.DataAdapter.Base, WEBLib.DataGrid.DataAdapter.XData,
  libdatagrid;

type
  TFTasksDataGrid = class(TWebForm)
    xdwcTasks: TXDataWebClient;
    dataGridTasks: TWebDataGrid;
    btnReload: TWebButton;
    btnAddRow: TWebButton;
    procedure WebFormCreate(Sender: TObject);
    procedure btnReloadClick(Sender: TObject);
    procedure btnAddRowClick(Sender: TObject);
  private
    FProjectId: string;
    procedure SetProjectTitle(const AProjectId: string);
    [async] procedure LoadTasks(const AProjectId: string);
  public
  end;

var
  FTasksDataGrid: TFTasksDataGrid;

implementation

uses
  ConnectionModule;

{$R *.dfm}

procedure TFTasksDataGrid.WebFormCreate(Sender: TObject);
begin
  xdwcTasks.Connection := DMConnection.ApiConnection;
  FProjectId := 'WPR0001';
  SetProjectTitle(FProjectId);
  LoadTasks(FProjectId);

end;

procedure TFTasksDataGrid.SetProjectTitle(const AProjectId: string);
begin
  TJSHTMLElement(document.getElementById('lbl_project_name')).innerText := AProjectId;
end;

procedure TFTasksDataGrid.btnReloadClick(Sender: TObject);
begin
  LoadTasks(FProjectId);
end;

procedure TFTasksDataGrid.btnAddRowClick(Sender: TObject);
begin
  dataGridTasks.InsertNewRow;
  dataGridTasks.EnsureLastRowVisible;
end;

[async] procedure TFTasksDataGrid.LoadTasks(const AProjectId: string);
var
  response: TXDataClientResponse;
  resultObj, taskObj: TJSObject;
  tasksArray, itemsArray, flatItems: TJSArray;
  taskIndex, itemIndex: Integer;
begin
  response := await(xdwcTasks.RawInvokeAsync('IApiService.GetProjectTasks', [AProjectId]));

  resultObj := TJSObject(response.Result);
  tasksArray := TJSArray(resultObj['data']);
  flatItems := TJSArray.new;

  for taskIndex := 0 to tasksArray.Length - 1 do
  begin
    taskObj := TJSObject(tasksArray[taskIndex]);
    itemsArray := TJSArray(taskObj['items']);

    for itemIndex := 0 to itemsArray.Length - 1 do
      flatItems.push(itemsArray[itemIndex]);
  end;

  dataGridTasks.LoadFromJSON(TJSObject(flatItems));
end;






end.

