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;
    xdwdsUnitsAgencyHeader: TStringField;
    xdwdsUnitsUnitId: TStringField;
    xdwdsUnitsUnitName: TStringField;
    xdwdsUnitsLocation: TStringField;
    xdwdsUnitsStatus: TStringField;
    xdwdsUnitsOfficer1: TStringField;
    xdwdsUnitsOfficer2: TStringField;
    xdwdsUnitsCallType: TStringField;
    xdwdsUnitsAgency: TStringField;
    xdwdsUnitsAgencyName: TStringField;
    xdwdsUnitsAgencyType: TStringField;
    xdwdsUnitsCanShowMap: TStringField;
    xdwdsUnitsMapButtonClass: TStringField;
    xdwdsUnitsMapButtonDisabled: TStringField;
    xdwdsUnitsMapButtonTitle: TStringField;
    xdwdsUnitsComplaintHeader: TStringField;
    procedure WebFormCreate(Sender: TObject);
  private
    FLoading: Boolean;
    FFirstLoad: Boolean;
    [async] procedure GetUnits;
    procedure HandleListClick(e: TJSMouseEvent);
  public
    procedure RefreshData;
    procedure ApplyWsData(aRespObj: TJSObject);
  end;

var
  FViewUnits: TFViewUnits;

implementation

{$R *.dfm}


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

  asm
    if (!window.showUnitDetails) {
      window.showUnitDetails = function (id) {
        pas['View.Main'].FViewMain.ShowUnitDetails(id);
      };
    }
  end;
end;


procedure TFViewUnits.HandleListClick(e: TJSMouseEvent);
var
  el: TJSElement;
  btn: TJSElement;
  unitId: string;
  canShowMap: 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
      canShowMap := string(TJSHtmlElement(btn).getAttribute('data-canmap'));

      e.preventDefault;
      e.stopPropagation;

      if not SameText(canShowMap, 'true') then
        Exit;

      unitId := string(TJSHtmlElement(btn).getAttribute('data-unitid'));

      asm
        pas['View.Main'].FViewMain.ShowMapFocusUnit(unitId);
      end;
    end;
  end;
end;


[async] procedure TFViewUnits.GetUnits;
var
  xdcResponse: TXDataClientResponse;
  respObj: TJSObject;
  unitCount: Integer;
begin
  if FLoading then
    Exit;

  FLoading := True;

  if FFirstLoad then
    Utils.ShowSpinner('spinner');

  try
    try
      xdcResponse := await(xdwcUnits.RawInvokeAsync('IApiService.GetUnitList', []));
      respObj := TJSObject(xdcResponse.Result);

      xdwdsUnits.Close;
      xdwdsUnits.SetJsonData(respObj['data']);
      xdwdsUnits.Open;

      unitCount := Integer(respObj['count']);
      lblEntries.Caption := Format('%d units', [unitCount]);
    except
      on E: EXDataClientRequestException do
        Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
      on E: Exception do
        Utils.ShowErrorModal(E.Message);
    end;
  finally
    if FFirstLoad then
      Utils.HideSpinner('spinner');
    FFirstLoad := False;

    FLoading := False;
  end;
end;

procedure TFViewUnits.RefreshData;
begin
  Console.Log('Units.RefreshData');
  GetUnits;
end;

procedure TFViewUnits.ApplyWsData(aRespObj: TJSObject);
var
  unitCount: Integer;
begin
  if FLoading then
    Exit;

  xdwdsUnits.Close;
  xdwdsUnits.SetJsonData(aRespObj['data']);
  xdwdsUnits.Open;

  unitCount := Integer(aRespObj['count']);
  lblEntries.Caption := Format('%d units', [unitCount]);
end;

end.
