unit View.Units;

interface

uses
  System.SysUtils, System.Classes, Web, WEBLib.Graphics, WEBLib.Forms, WEBLib.Dialogs,
  Vcl.Controls, Vcl.StdCtrls, WEBLib.StdCtrls, WEBLib.Controls, WEBLib.Grids, WebLib.Lists,
  XData.Web.Client, WEBLib.ExtCtrls, XData.Web.JsonDataset,
  XData.Web.Dataset, XData.Web.Connection, Vcl.Forms, DateUtils, WEBLib.DBCtrls, System.Generics.Collections,
  WEBLib.Menus, WEBLib.JSON, Auth.Service, WebLib.Storage, ConnectionModule, App.Types,
  WEBLib.DB, Data.DB, XData.Web.DatasetCommon, JS, XData.Model.Classes, Utils;

type
  TFViewUnits = class(TWebForm)
    dblUnitsList: TWebDBListControl;
    btnRefresh: TWebButton;
    btnGroup: TWebButton;
    btnFilter: TWebButton;
    wdsUnits: TWebDataSource;
    xdwdsUnits: TXDataWebDataSet;
    xdwcUnits: TXDataWebClient;
    lblEntries: TWebLabel;
    xdwdsUnitsDistrictHeader: TStringField;
    xdwdsUnitsUnitId: TStringField;
    xdwdsUnitsUnitName: TStringField;
    xdwdsUnitsLocation: TStringField;
    xdwdsUnitsStatus: TStringField;
    xdwdsUnitsOfficer1: TStringField;
    xdwdsUnitsOfficer2: TStringField;
    procedure WebFormCreate(Sender: TObject);
    procedure btnRefreshClick(Sender: TObject);
  private
    [async] procedure GetUnits;
  public

  end;

var
  FViewUnits: TFViewUnits;

implementation

{$R *.dfm}




procedure TFViewUnits.WebFormCreate(Sender: TObject);
begin
  console.log('Units.WebFormCreate: Starting setup...');
  DMConnection.ApiConnection.Connected := True;
  console.log('API connection active:', DMConnection.ApiConnection.Connected);
  GetUnits;
end;

procedure TFViewUnits.btnRefreshClick(Sender: TObject);
begin
  GetUnits;
end;

procedure TFViewUnits.GetUnits;
var
  xdcResponse: TXDataClientResponse;
  respObj: TJSObject;
  unitCount: Integer;
begin
  console.log('GetUnits: Invoking API...');
  Utils.ShowSpinner('spinner');
  try
    try
      xdcResponse := await(xdwcUnits.RawInvokeAsync('IApiService.GetUnitList', []));
      console.log('RawInvoke returned:', xdcResponse.Result);

      respObj := TJSObject(xdcResponse.Result);

      xdwdsUnits.Close;
      console.log('Units dataset closed');

      xdwdsUnits.SetJsonData(respObj['data']);
      console.log('JsonData set on units dataset:', respObj['data']);

      xdwdsUnits.Open;
      console.log('Units dataset opened. Record count:', xdwdsUnits.RecordCount);

      unitCount := Integer(respObj['count']);
      lblEntries.Caption := Format('%d units', [unitCount]);
      console.log('Units label updated:', lblEntries.Caption);
    except
      on E: EXDataClientRequestException do
      begin
        console.log('XData exception (units):', E.ErrorResult.ErrorMessage);
        Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
      end;
    end;
  finally
    Utils.HideSpinner('spinner');
    console.log('GetUnits complete');
  end;
end;


end.
