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;
    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;
    procedure HandleListClick(e: TJSMouseEvent);
  public

  end;

var
  FViewUnits: TFViewUnits;

implementation

{$R *.dfm}


procedure TFViewUnits.WebFormCreate(Sender: TObject);
begin
  DMConnection.ApiConnection.Connected := True;
  Document.addEventListener('click', @HandleListClick);
  tmrRefresh.Enabled := False;
  GetUnits;
  tmrRefresh.Enabled := True;

  asm
    if (!window.showUnitDetails) {
      window.showUnitDetails = function (id) {
        console.log('JS bridge showUnitDetails called, id=', id);
        try {
          pas['View.Main'].FViewMain.ShowUnitDetails(id);
        } catch (e) {
          console.log('Error in TFViewMain.ShowUnitDetails', e);
        }
      };
    }
  end;
end;


procedure TFViewUnits.HandleListClick(e: TJSMouseEvent);
var
  el: TJSElement;
  btn: TJSElement;
  unitId: string;
begin
  btn := nil;
  el := TJSElement(e.target);

  asm
    btn = (el && el.closest) ? el.closest('.btn-unit-details') : null;
  end;

  if (btn <> nil) and (btn is TJSHtmlElement) then
  begin
    unitId := string(TJSHtmlElement(btn).getAttribute('data-unitid'));
    e.preventDefault;
    e.stopPropagation;

    asm
      if (window.showUnitDetails) window.showUnitDetails(unitId);
    end;
  end
  else
  begin
    btn := nil;

    asm
      btn = (el && el.closest) ? el.closest('.btn-unit-map') : null;
    end;

    if (btn <> nil) and (btn is TJSHtmlElement) then
    begin
      unitId := string(TJSHtmlElement(btn).getAttribute('data-unitid'));
      e.preventDefault;
      e.stopPropagation;

      asm
        try {
          pas['View.Main'].FViewMain.ShowMapFocusUnit(unitId);
        } catch (e) {
          console.log('ShowMapFocusUnit failed', e);
        }
      end;
    end;
  end;
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
    FLoading := False;
    Utils.HideSpinner('spinner');
    console.log('GetUnits complete');
  end;
end;

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


end.
