unit View.Complaints;

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
  TFViewComplaints = class(TWebForm)
    xdwcComplaints: TXDataWebClient;
    xdwdsComplaints: TXDataWebDataSet;
    dblComplaintsList: TWebDBListControl;
    xdwdsComplaintsComplaint: TStringField;
    xdwdsComplaintsAgency: TStringField;
    xdwdsComplaintsPriority: TStringField;
    xdwdsComplaintsDispatchCodeDesc: TStringField;
    xdwdsComplaintsAddress: TStringField;
    xdwdsComplaintsStatus: TStringField;
    xdwdsComplaintsDispatchDistrict: TStringField;
    xdwdsComplaintsDateReported: TStringField;
    lblEntries: TWebLabel;
    wdsComplaints: TWebDataSource;
    xdwdsComplaintsComplaintId: TStringField;
    xdwdsComplaintsDistrictHeader: TStringField;
    xdwdsComplaintsStatusColor: TStringField;
    xdwdsComplaintsPriorityColor: TStringField;
    xdwdsComplaintsPriorityTextColor: TStringField;
    xdwdsComplaintsDistrictSector: TStringField;
    tmrRefresh: TWebTimer;
    procedure WebFormCreate(Sender: TObject);
    procedure btnRefreshClick(Sender: TObject);
    procedure tmrRefreshTimer(Sender: TObject);
    procedure WebFormDestroy(Sender: TObject);
  private
    FSelectProc: TSelectProc;
    FLoading: Boolean;
    [async] procedure GetComplaints;
    procedure HandleListClick(e: TJSMouseEvent);
  public
    property OnShowDetails: TSelectProc read FSelectProc write FSelectProc;
  end;

var
  FViewComplaints: TFViewComplaints;

implementation

{$R *.dfm}

procedure TFViewComplaints.WebFormCreate(Sender: TObject);
begin
  Document.addEventListener('click', @HandleListClick);
  ShowSpinner('spinner');
  tmrRefresh.Enabled := False;
  GetComplaints;
  tmrRefresh.Enabled := True;
  asm
    if (!window.showComplaintDetails) {
      window.showComplaintDetails = function (id) {
        console.log('JS bridge showComplaintDetails called, id=', id);
        try {
          pas['View.Main'].FViewMain.ShowComplaintDetails(id);
        } catch (e) {
          console.log('Error in TFViewMain.ShowComplaintDetails', e);
        }
      };
    }
  end;
end;

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

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

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

    asm
      if (window.showComplaintDetails) window.showComplaintDetails(complaintId);
    end;
  end
  else
  begin
    btn := nil;

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

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

      asm
        try {
          pas['View.Main'].FViewMain.ShowMapFocusComplaint(complaintId);
        } catch (e) {
          console.log('ShowMapFocusComplaint failed', e);
        }
      end;
    end;
  end;
end;


procedure TFViewComplaints.WebFormDestroy(Sender: TObject);
begin
  Document.removeEventListener('click', @HandleListClick);
end;

//Note: jjHTML for individual complaint cards can be found in the twebdblistcontrol HTMLString property
procedure TFViewComplaints.btnRefreshClick(Sender: TObject);
begin
  GetComplaints;
end;

procedure TFViewComplaints.GetComplaints;
var
  xdcResponse: TXDataClientResponse;
  respObj: TJSObject;
  complaintsCount: Integer;
begin
  if FLoading then Exit;
  FLoading := True;

  try
    try
      xdcResponse := await(xdwcComplaints.RawInvokeAsync('IApiService.GetComplaintList', []));

      respObj := TJSObject(xdcResponse.Result);

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

      complaintsCount := Integer(respObj['count']);
      lblEntries.Caption := Format('%d active complaints', [complaintsCount]);
    except
      on E: EXDataClientRequestException do
      begin
        Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
      end;
    end;
  finally
  end;
  FLoading := False;
  HideSpinner('spinner');
end;


procedure TFViewComplaints.tmrRefreshTimer(Sender: TObject);
begin
  GetComplaints;
end;

end.

