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;
    xdwdsComplaintsBusiness: TStringField;
    xdwdsComplaintsStatusTextColor: TStringField;
    xdwdsComplaintsAgencyLine: TStringField;
    procedure WebFormCreate(Sender: TObject);
    procedure WebFormDestroy(Sender: TObject);
  private
    FSelectProc: TSelectProc;
    FLoading: Boolean;
    FFirstLoad: Boolean;
    [async] procedure GetComplaints;
    procedure HandleListClick(e: TJSMouseEvent);
    procedure ShowHideBusinessRows;
  public
    property OnShowDetails: TSelectProc read FSelectProc write FSelectProc;
    procedure RefreshData;
  end;

var
  FViewComplaints: TFViewComplaints;

implementation

{$R *.dfm}

procedure TFViewComplaints.WebFormCreate(Sender: TObject);
begin
  Document.addEventListener('click', @HandleListClick);
  FFirstLoad := True;
  GetComplaints;
  asm
    if (!window.showComplaintDetails) {
      window.showComplaintDetails = function (id) {
        pas['View.Main'].FViewMain.ShowComplaintDetails(id);
      };
    }
  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
[async] procedure TFViewComplaints.GetComplaints;
var
  xdcResponse: TXDataClientResponse;
  respObj: TJSObject;
  complaintsCount: Integer;
begin
  if FLoading then
    Exit;

  FLoading := True;

  if FFirstLoad then
    ShowSpinner('spinner');
  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;
    if FFirstLoad then
    begin
      HideSpinner('spinner');
      FFirstLoad := False;
    end;
  end;
end;

procedure TFViewComplaints.RefreshData;
begin
  Console.Log('Complaints.RefreshData');
  GetComplaints;
end;

end.

