unit View.TasksDBGrid;

interface

uses
  System.SysUtils, System.Classes, JS, Web, WEBLib.Graphics, WEBLib.Controls,
  WEBLib.Forms, WEBLib.Dialogs, WEBLib.Grids, Vcl.Controls, Vcl.Grids,
  WEBLib.DBCtrls, Data.DB, WEBLib.DB, XData.Web.JsonDataset, XData.Web.Dataset,
  XData.Web.Client, ConnectionModule, Vcl.StdCtrls, WEBLib.StdCtrls;

type
  TFTasksDBGrid = class(TWebForm)
    xdwcTasks: TXDataWebClient;
    wdsTasks: TWebDataSource;
    xdwdsTasks: TXDataWebDataSet;
    xdwdsTaskstaskID: TStringField;
    xdwdsTasksapplication: TStringField;
    xdwdsTasksversion: TStringField;
    xdwdsTaskstaskDate: TStringField;
    xdwdsTasksreportedBy: TStringField;
    xdwdsTasksassignedTo: TStringField;
    xdwdsTasksstatus: TStringField;
    xdwdsTasksstatusDate: TStringField;
    xdwdsTasksformSection: TStringField;
    xdwdsTasksissue: TStringField;
    xdwdsTasksnotes: TStringField;
    btnReload: TWebButton;
    btnAddRow: TWebButton;
    dbGridTasks: TWebDBGrid;
    procedure btnAddRowClick(Sender: TObject);
    procedure btnReloadClick(Sender: TObject);
    procedure WebFormCreate(Sender: TObject);
  private
    FProjectId: string;
    [async] procedure LoadTasks(const AProjectId: string);
    procedure SetProjectTitle(const AProjectId: string);
  public
    { Public declarations }
  end;

var
  FTasksDBGrid: TFTasksDBGrid;

implementation

{$R *.dfm}

procedure TFTasksDBGrid.WebFormCreate(Sender: TObject);
begin
  wdsTasks.DataSet := xdwdsTasks;
  dbGridTasks.DataSource := wdsTasks;

  FProjectId := 'WPR0001';
  SetProjectTitle(FProjectId);
  LoadTasks(FProjectId);
end;


procedure TFTasksDBGrid.btnAddRowClick(Sender: TObject);
begin
  xdwdsTasks.Append;
  xdwdsTaskstaskID.AsString := FProjectId;
  xdwdsTasks.Post;
end;

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


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


[async] procedure TFTasksDBgrid.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;

  xdwdsTasks.Close;
  xdwdsTasks.SetJsonData(flatItems);
  xdwdsTasks.Open;
end;

end.