unit View.Main;

interface

uses
  System.SysUtils, System.Classes, JS, Web, WEBLib.Graphics, WEBLib.Controls,
  WEBLib.Forms, WEBLib.Dialogs, WEBLib.ExtCtrls, Vcl.Controls, Vcl.StdCtrls,
  WEBLib.StdCtrls, Data.DB, XData.Web.JsonDataset, XData.Web.Dataset,
  App.Types, ConnectionModule, XData.Web.Client;

type
  TFViewMain = class(TWebForm)
    lblUsername: TWebLabel;
    wllblUserProfile: TWebLinkLabel;
    wllblLogout: TWebLinkLabel;
    WebPanel1: TWebPanel;
    WebMessageDlg1: TWebMessageDlg;
    lblAppTitle: TWebLabel;
    WebMemo1: TWebMemo;
    xdwcBadgeCounts: TXDataWebClient;
    lblCallsList: TWebLinkLabel;
    lblUsers: TWebLinkLabel;
    btnMap: TWebButton;
    btnComplaints: TWebButton;
    btnUnits: TWebButton;
    tmrBadgeCounts: TWebTimer;
    lblMainTitle: TWebLabel;
    procedure WebFormCreate(Sender: TObject);
    procedure mnuLogoutClick(Sender: TObject);
    procedure wllblUserProfileClick(Sender: TObject);
    procedure wllblLogoutClick(Sender: TObject);
    procedure lblCallsListClick(Sender: TObject);
    procedure lblUsersClick(Sender: TObject);
    procedure btnUnitsClick(Sender: TObject);
    procedure btnComplaintsClick(Sender: TObject);
    procedure btnMapClick(Sender: TObject);
    procedure tmrBadgeCountsTimer(Sender: TObject);
  private
    { Private declarations }
    FUserInfo: string;
    FSearchSettings: string;
    FChildForm: TWebForm;
    FLogoutProc: TLogoutProc;
    FSearchProc: TSearchProc;
    procedure ShowCrudForm( AFormClass: TWebFormClass );
    //procedure EditUser( AParam, BParam, CParam, DParam, EParam: string);
    function GetUserInfo: string;
    [async] procedure RefreshBadgesAsync;
    procedure ShowUnitDetails(UnitId: string);
    procedure SetHeaderTitle(const title: string);
  public
    { Public declarations }
    class procedure Display(LogoutProc: TLogoutProc);
    procedure ShowForm( AFormClass: TWebFormClass );
    procedure EditUser( Mode, FullName, Username, Phone, Email: string; admin, active: boolean);
    procedure ShowUserForm(Info: string);
    procedure ShowComplaintDetails(ComplaintId: string);
    procedure SetActiveNavButton(const BtnId: string);
    procedure ShowMapFocusUnit(const unitId: string);
    procedure ShowMapFocusComplaint(const complaintId: string);
  end;

var
  FViewMain: TFViewMain;

implementation

uses
  Auth.Service,
  View.Login,
  View.UserProfile,
  View.Map,
  View.Complaints,
  View.ComplaintDetails,
  View.Units,
  View.Admin,
  View.Users,
  View.EditUser,
  View.UnitDetails,
  Utils;

{$R *.dfm}

procedure TFViewMain.WebFormCreate(Sender: TObject);
var
  userName: string;
begin
  FUserInfo := GetUserInfo;
  userName := JS.toString(AuthService.TokenPayload.Properties['user_name']);
  lblUsername.Caption := ' ' + userName.ToLower + ' ';
  FChildForm := nil;
  if (not (JS.toBoolean(AuthService.TokenPayload.Properties['user_admin'])))  then
    lblUsers.Visible := false;
  Utils.HideSpinner('spinner');
  ShowForm(TFViewMap);
  SetHeaderTitle('Map');
  RefreshBadgesAsync;
end;

procedure TFViewMain.SetHeaderTitle(const title: string);
var el: TJSElement;
begin
  el := Document.getElementById('lbl_main_title');
  if el <> nil then
    el.innerHTML := title
  else
    console.log('SetHeaderTitle: lbl_main_title not found');
end;


procedure TFViewMain.lblUsersClick(Sender: TObject);
begin
  ShowForm(TFViewUsers);
end;

procedure TFViewMain.lblCallsListClick(Sender: TObject);
begin
  ShowForm(TFViewComplaints);
end;

procedure TFViewMain.mnuLogoutClick(Sender: TObject);
begin
  FLogoutProc;
end;


procedure TFViewMain.wllblLogoutClick(Sender: TObject);
begin
  FLogoutProc;
end;


procedure TFViewMain.wllblUserProfileClick(Sender: TObject);
begin
    ShowCrudForm(TFViewUserProfile);
end;


function TFViewMain.GetUserInfo: string;
var
  userStr: string;
begin
  userStr := '?username=' + JS.toString(AuthService.TokenPayload.Properties['user_name']);
  userStr := userStr + '&fullname=' + JS.toString(AuthService.TokenPayload.Properties['user_fullname']);
  userStr := userStr + '&agency=' + JS.toString(AuthService.TokenPayload.Properties['user_agency']);
  userStr := userStr + '&badge=' + JS.toString(AuthService.TokenPayload.Properties['user_badge']);
  userStr := userStr + '&userid=' + JS.toString(AuthService.TokenPayload.Properties['user_id']);
  userStr := userStr + '&personnelid=' + JS.toString(AuthService.TokenPayload.Properties['user_personnelid']);

  Result := userStr;
end;


procedure TFViewMain.btnComplaintsClick(Sender: TObject);
begin
  SetHeaderTitle('Complaints');
  SetActiveNavButton('view.main.btncomplaints');
  ShowForm(TFViewComplaints);

 if (FChildForm is TFViewComplaints) then
   TFViewComplaints(FChildForm).OnShowDetails :=
     procedure(AComplaintId: string)
     begin
       ShowComplaintDetails(AComplaintId);
    end;
end;

procedure TFViewMain.btnMapClick(Sender: TObject);
begin
  SetHeaderTitle('Map');
  SetActiveNavButton('view.main.btnmap');
  ShowForm(TFViewMap);
end;

procedure TFViewMain.btnUnitsClick(Sender: TObject);
begin
  SetHeaderTitle('Units');
  SetActiveNavButton('view.main.btnunits');
  ShowForm(TFViewUnits);
end;

class procedure TFViewMain.Display(LogoutProc: TLogoutProc);
begin
  if Assigned(FViewMain) then
    FViewMain.Free;
  FViewMain := TFViewMain.CreateNew;
  FViewMain.FLogoutProc := LogoutProc;
end;


procedure TFViewMain.ShowCrudForm(AFormClass: TWebFormClass);
begin
  ShowForm(AFormClass);
end;


procedure TFViewMain.ShowForm(AFormClass: TWebFormClass);
begin
  if Assigned(FChildForm) then
    FChildForm.Free;
  Application.CreateForm(AFormClass, WebPanel1.ElementID, FChildForm);
end;

procedure TFViewMain.EditUser( Mode, FullName, Username, Phone, Email: string; Admin, Active: boolean);
begin
  if Assigned(FChildForm) then
    FChildForm.Free;
  FChildForm := TFViewEditUser.CreateForm(WebPanel1.ElementID, Mode, FullName, Username, Phone, Email, Admin, Active);
end;

procedure TFViewMain.ShowUserForm(Info: string);
begin
  if Assigned(FChildForm) then
    FChildForm.Free;
  FChildForm := TFViewUsers.CreateForm(WebPanel1.ElementID, Info);
end;

procedure TFViewMain.ShowComplaintDetails(ComplaintId: string);
begin
  SetHeaderTitle('Complaint Details');
  if Assigned(FChildForm) then
    FChildForm.Free;
  FChildForm := TFViewComplaintDetails.CreateForm(WebPanel1.ElementID, ComplaintId);
end;

procedure TFViewMain.ShowUnitDetails(UnitId: string);
begin
  SetHeaderTitle('Unit Details');
  if Assigned(FChildForm) then
    FChildForm.Free;
  FChildForm := TFViewUnitDetails.CreateForm(WebPanel1.ElementID, UnitId);
end;


procedure TFViewMain.SetActiveNavButton(const btnId: string);
var
  m, c, u: TJSHTMLElement;
begin
  m := TJSHTMLElement(btnMap.ElementHandle);
  c := TJSHTMLElement(btnComplaints.ElementHandle);
  u := TJSHTMLElement(btnUnits.ElementHandle);

  // clear
  m.classList.remove('active');
  c.classList.remove('active');
  u.classList.remove('active');

  // set
  if btnId = 'view.main.btnmap' then
    m.classList.add('active')
  else if btnId = 'view.main.btncomplaints' then
    c.classList.add('active')
  else if btnId = 'view.main.btnunits' then
    u.classList.add('active');
end;


procedure TFViewMain.tmrBadgeCountsTimer(Sender: TObject);
begin
  console.log('Badges Refreshed');
  RefreshBadgesAsync;
end;


[async] procedure TFViewMain.RefreshBadgesAsync;
var
  resp: TXDataClientResponse;
  badgeObj: TJSObject;
  el: TJSElement;
begin
  try
    resp := await(xdwcBadgeCounts.RawInvokeAsync('IApiService.GetBadgeCounts', []));
    badgeObj := TJSObject(resp.Result);

    el := Document.getElementById('view.main.badgecomplaints');
    if Assigned(el) then
      TJSHtmlElement(el).innerText := string(badgeObj['BadgeComplaints']);

    el := Document.getElementById('view.main.badgeunits');
    if Assigned(el) then
      TJSHtmlElement(el).innerText := string(badgeObj['BadgeUnits']);
  except
    on E: Exception do
    begin
      el := Document.getElementById('view.main.badgecomplaints');
      if Assigned(el) then TJSHtmlElement(el).innerText := '—';
      el := Document.getElementById('view.main.badgeunits');
      if Assigned(el) then TJSHtmlElement(el).innerText := '—';
      Console.Log('Badge refresh error: ' + E.Message);
    end;
  end;
end;


procedure TFViewMain.ShowMapFocusUnit(const unitId: string);
var
  pendingUnitId: string;
begin
  SetHeaderTitle('Map');
  SetActiveNavButton('view.main.btnmap');
  ShowForm(TFViewMap);

  pendingUnitId := unitId;

  window.setTimeout(
    procedure
    begin
      if (FChildForm <> nil) and (FChildForm is TFViewMap) then
        TFViewMap(FChildForm).FocusUnit(pendingUnitId);
    end, 50);
end;

procedure TFViewMain.ShowMapFocusComplaint(const complaintId: string);
var
  pendingComplaintId: string;
begin
  SetHeaderTitle('Map');
  SetActiveNavButton('view.main.btnmap');
  ShowForm(TFViewMap);

   pendingComplaintId := complaintId;

  window.setTimeout(
    procedure
    begin
      if (FChildForm <> nil) and (FChildForm is TFViewMap) then
        TFViewMap(FChildForm).FocusComplaint(pendingComplaintId);
    end, 50);
end;


end.
