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;
    btnRefresh: TWebButton;
    btnGroup: TWebButton;
    btnFilter: TWebButton;
    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;
end;

procedure TFViewComplaints.HandleListClick(e: TJSMouseEvent);
var el: TJSElement; id: string;
begin
  el := TJSElement(e.target);
  if (el is TJSHtmlElement) and TJSHtmlElement(el).classList.contains('complaint-details-btn') then
  begin
    id := string(TJSHtmlElement(el).dataset['id']); // comes from (%ComplaintId%)
    e.preventDefault;
    e.stopPropagation;

   if Assigned(FSelectProc) then
     FSelectProc(id);
  end;
end;



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

//HTML 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;

  console.log('GetComplaints: Invoking API...');


  try
    try
      xdcResponse := await(xdwcComplaints.RawInvokeAsync('IApiService.GetComplaintList', []));
      console.log('RawInvoke returned:', xdcResponse.Result);

      respObj := TJSObject(xdcResponse.Result);

      xdwdsComplaints.Close;
      console.log('Dataset closed');

      xdwdsComplaints.SetJsonData(respObj['data']);
      console.log('JsonData set on dataset:', respObj['data']);

      xdwdsComplaints.Open;
      console.log('PriorityColor field name = ' +
            xdwdsComplaintsPriorityColor.FieldName +
            ' sample value = ' +
            xdwdsComplaintsPriorityColor.AsString);

      if xdwdsComplaints.RecordCount > 0 then
      begin
        console.log('First record - Complaint:' + xdwdsComplaints.FieldByName('Complaint').AsString);
      end;

      complaintsCount := Integer(respObj['count']);
      lblEntries.Caption := Format('%d active complaints', [complaintsCount]);
      console.log('Label updated:' + lblEntries.Caption);
    except
      on E: EXDataClientRequestException do
      begin
        console.log('XData exception:' + E.ErrorResult.ErrorMessage);
        Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
      end;
    end;
  finally

    console.log('GetComplaints complete');
  end;
  HideSpinner('spinner');
end;


procedure TFViewComplaints.tmrRefreshTimer(Sender: TObject);
begin
  GetComplaints;
  console.log('tmrRefreshTimer fired');
end;

end.

