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;
    xdwdsUnitsCallType: TStringField;
    tmrRefresh: TWebTimer;
    procedure WebFormCreate(Sender: TObject);
    procedure btnRefreshClick(Sender: TObject);
    procedure tmrRefreshTimer(Sender: TObject);
  private
    FLoading: Boolean;
    [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);

  tmrRefresh.Enabled := False;
  GetUnits;
  tmrRefresh.Enabled := True;

  {$IFNDEF WIN32}
  asm
    var root = pas.TFViewUnits(Self).dblUnitsList.ElementHandle;
    if (root && !root.__emiDelegated) {
      root.__emiDelegated = true;

      root.addEventListener('click', function (e) {
        // Look for a click on, or inside, the details button
        var btn = e.target && e.target.closest('.btn-unit-details');
        if (!btn || !root.contains(btn)) return;

        e.preventDefault();
        e.stopPropagation();

        var unitId = btn.getAttribute('data-unitid') || '';
        pas.TFViewUnits(Self).OpenUnitDetails(unitId);
      }, { passive: true });
    }
  end;
  {$ENDIF}
end;

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

procedure TFViewUnits.GetUnits;
var
  xdcResponse: TXDataClientResponse;
  respObj: TJSObject;
  unitCount: Integer;
begin
  if FLoading then Exit;
  FLoading := True;

  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;

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


end.
