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;
    xdwdsComplaintsBusiness: TStringField;
    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);
    procedure ShowHideBusinessRows;
  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);
  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.ShowHideBusinessRows;
var
  nodes: TJSNodeList;
  i: Integer;
  el: TJSHTMLElement;
  businessText: string;
begin
  nodes := document.querySelectorAll('.complaint-business');
  for i := 0 to nodes.length - 1 do
  begin
    el := TJSHTMLElement(nodes.item(i));
    businessText := string(el.getAttribute('data-business'));
    if Trim(businessText) <> '' then
      el.classList.remove('d-none')
    else
      el.classList.add('d-none');
  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
        pas['View.Main'].FViewMain.ShowMapFocusComplaint(complaintId);
      end;
    end;
  end;
end;


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

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

[async] 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;

      ShowHideBusinessRows;

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

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

end.

