unit View.UnitDetails;

interface

uses
  System.SysUtils, System.Classes, JS, Web,
  WEBLib.Forms, WEBLib.Dialogs, WEBLib.Graphics,
  XData.Web.Client, XData.Web.JsonDataset, XData.Web.Dataset,
  ConnectionModule,
  Utils,
  Data.DB, WEBLib.DB,
  Vcl.Controls, WEBLib.Controls, WEBLib.Grids, WEBLib.DBCtrls, Vcl.StdCtrls,
  WEBLib.StdCtrls;

type
  TFViewUnitDetails = class(TWebForm)
    xdwcUnitDetails: TXDataWebClient;

    // Details (single-object) dataset
    xdwdsUnitDetails: TXDataWebDataSet;
    xdwdsUnitDetailsUnitId: TStringField;
    xdwdsUnitDetailsUnitName: TStringField;
    xdwdsUnitDetailsCarNumberDesc: TStringField;
    xdwdsUnitDetailsDistrict: TStringField;
    xdwdsUnitDetailsLocation: TStringField;
    xdwdsUnitDetailsStatus: TStringField;
    xdwdsUnitDetailsOfficer1Lname: TStringField;
    xdwdsUnitDetailsOfficer1Fname: TStringField;
    xdwdsUnitDetailsOfficer1Empnum: TStringField;
    xdwdsUnitDetailsOfficer2Lname: TStringField;
    xdwdsUnitDetailsOfficer2Fname: TStringField;
    xdwdsUnitDetailsOfficer2Empnum: TStringField;
    xdwdsUnitDetailsUpdateTime: TStringField;

    // Logs (array) dataset + table
    xdwdsUnitLogs: TXDataWebDataSet;
    wdsUnitLogs: TWebDataSource;
    tblLogs: TWebDBTableControl;
    xdwdsUnitLogsComplaint: TStringField;
    xdwdsUnitLogsLog: TStringField;
    xdwdsUnitLogsLogTime: TStringField;
    btnUnitViewOnMap: TWebButton;
    procedure btnUnitViewOnMapClick(Sender: TObject);
  private
    FUnitId: string;
    FLoading: Boolean;

    procedure InitializeForm;

    procedure SetTextById(const elementId, value: string);
    procedure SetHiddenById(const elementId: string; hidden: Boolean);

    function FormatOfficer(const lname, fname, empnum: string): string;

    [async] procedure LoadUnitAsync;
    [async] procedure LoadLogsAsync;

  public
    class function CreateForm(AElementID, UnitId: string): TWebForm;
  end;

var
  FViewUnitDetails: TFViewUnitDetails;

implementation

uses
  View.Main,
  View.Units;

{$R *.dfm}

procedure TFViewUnitDetails.btnUnitViewOnMapClick(Sender: TObject);
begin
  if Assigned(FViewMain) then
    FViewMain.ShowMapFocusUnit(FUnitId);
    console.log('btnViewOnMapClick fired, FUnitId=' + FUnitId);
end;

class function TFViewUnitDetails.CreateForm(AElementID, UnitId: string): TWebForm;

  procedure AfterCreate(AForm: TObject);
  begin
    with TFViewUnitDetails(AForm) do
    begin
      FUnitId := UnitId;
      InitializeForm;
    end;
  end;

begin
  Application.CreateForm(TFViewUnitDetails, AElementID, Result, @AfterCreate);
end;

procedure TFViewUnitDetails.InitializeForm;
begin
  xdwcUnitDetails.Connection := DMConnection.ApiConnection;
  xdwdsUnitDetails.Connection := DMConnection.ApiConnection;
  xdwdsUnitLogs.Connection := DMConnection.ApiConnection;

  FLoading := False;

  LoadUnitAsync;
end;


procedure TFViewUnitDetails.SetTextById(const elementId, value: string);
var
  el: TJSElement;
begin
  el := Document.getElementById(elementId);
  if el <> nil then
    TJSHtmlElement(el).innerText := value;
end;

procedure TFViewUnitDetails.SetHiddenById(const elementId: string; hidden: Boolean);
var
  el: TJSHTMLElement;
begin
  el := TJSHTMLElement(Document.getElementById(elementId));
  if el = nil then
    Exit;

  if hidden then
    el.classList.add('d-none')
  else
    el.classList.remove('d-none');
end;

function TFViewUnitDetails.FormatOfficer(const lname, fname, empnum: string): string;
var
  nameText: string;
begin
  nameText := Trim(lname);
  if nameText = '' then
    Exit('');

  if Trim(fname) <> '' then
    nameText := nameText + ', ' + Trim(fname);

  if Trim(empnum) <> '' then
    nameText := nameText + ' (' + Trim(empnum) + ')';

  Result := nameText;
end;

[async] procedure TFViewUnitDetails.LoadUnitAsync;
var
  resp: TXDataClientResponse;
  rootObj: TJSObject;
  dataObj: TJSObject;
  summaryTitle: string;
  officer1Text: string;
  officer2Text: string;
begin
  if FLoading then
    Exit;

  FLoading := True;
  Utils.ShowSpinner('spinner');

  try
    resp := await(xdwcUnitDetails.RawInvokeAsync('IApiService.GetUnitDetails', [FUnitId]));
    rootObj := TJSObject(resp.Result);
    dataObj := TJSObject(rootObj['data']);

    xdwdsUnitDetails.Close;
    xdwdsUnitDetails.SetJsonData(dataObj);
    xdwdsUnitDetails.Open;

    summaryTitle := xdwdsUnitDetailsUnitName.AsString;
    if Trim(summaryTitle) <> '' then
      SetTextById('lbl_summary_title', 'Summary for Unit ' + summaryTitle)
    else
      SetTextById('lbl_summary_title', 'Summary for Unit ' + xdwdsUnitDetailsUnitId.AsString);

    SetTextById('lbl_car', xdwdsUnitDetailsCarNumberDesc.AsString);
    SetTextById('lbl_unit_name', xdwdsUnitDetailsUnitName.AsString);
    SetTextById('lbl_district', xdwdsUnitDetailsDistrict.AsString);
    SetTextById('lbl_location', xdwdsUnitDetailsLocation.AsString);
    SetTextById('lbl_status', xdwdsUnitDetailsStatus.AsString);
    SetTextById('lbl_updated', xdwdsUnitDetailsUpdateTime.AsString);

    officer1Text := FormatOfficer(
      xdwdsUnitDetailsOfficer1Lname.AsString,
      xdwdsUnitDetailsOfficer1Fname.AsString,
      xdwdsUnitDetailsOfficer1Empnum.AsString
    );

    officer2Text := FormatOfficer(
      xdwdsUnitDetailsOfficer2Lname.AsString,
      xdwdsUnitDetailsOfficer2Fname.AsString,
      xdwdsUnitDetailsOfficer2Empnum.AsString
    );

    SetTextById('lbl_officer1', officer1Text);
    SetTextById('lbl_officer2', officer2Text);


    await(LoadLogsAsync);

    Utils.HideSpinner('spinner');
    FLoading := False;
  except
    on E: EXDataClientRequestException do
    begin
      Utils.HideSpinner('spinner');
      FLoading := False;
      Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
    end;
    on E: Exception do
    begin
      Utils.HideSpinner('spinner');
      FLoading := False;
      Utils.ShowErrorModal(E.Message);
    end;
  end;
end;

[async] procedure TFViewUnitDetails.LoadLogsAsync;
var
  resp: TXDataClientResponse;
  rootObj: TJSObject;
  dataArr: TJSArray;
begin
  SetHiddenById('spinner_logs', False);

  try
    resp := await(xdwcUnitDetails.RawInvokeAsync('IApiService.GetUnitLogs', [FUnitId]));
    rootObj := TJSObject(resp.Result);
    dataArr := TJSArray(rootObj['data']);
    console.log('LoadLogsAsync Units rootObj: ' + rootObj.tostring);

    xdwdsUnitLogs.Close;
    xdwdsUnitLogs.SetJsonData(dataArr);
    xdwdsUnitLogs.Open;

    SetHiddenById('spinner_logs', True);
  except
    on E: EXDataClientRequestException do
    begin
      SetHiddenById('spinner_logs', True);
      Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
    end;
    on E: Exception do
    begin
      SetHiddenById('spinner_logs', True);
      Utils.ShowErrorModal(E.Message);
    end;
  end;
end;

end.

