unit View.QBInfo;

interface

uses
  System.SysUtils, System.Classes, JS, Web, WEBLib.Graphics, WEBLib.Controls,
  WEBLib.Forms, WEBLib.Dialogs, Vcl.Controls, Vcl.StdCtrls, WEBLib.StdCtrls,
  XData.Web.Client, ConnectionModule;

type
  TFQBInfo = class(TWebForm)
    lblConnected: TWebLabel;
    lblCompanyName: TWebLabel;
    lblCompanyID: TWebLabel;
    btnLinkToQB: TWebButton;
    XDataWebClient1: TXDataWebClient;
    lblLastRefresh: TWebLabel;
    btnClose: TWebButton;
    procedure btnLinkToQBClick(Sender: TObject);
    procedure WebFormCreate(Sender: TObject);
    procedure WebFormShow(Sender: TObject);
    procedure btnCloseClick(Sender: TObject);
  private
    { Private declarations }
    ClientID: string;
    [async] procedure GetQBInfo();
    [async] procedure GetQBLink();
  public
    { Public declarations }
  end;

var
  FQBInfo: TFQBInfo;

implementation

{$R *.dfm}

uses View.Main, Utils;

procedure TFQBInfo.btnLinkToQBClick(Sender: TObject);
begin
  GetQBLink();
end;

procedure TFQBInfo.WebFormCreate(Sender: TObject);
begin
  if not DMConnection.ApiConnection.Connected then
   begin
    DMConnection.ApiConnection.OpenAsync;
   end;
end;

procedure TFQBInfo.WebFormShow(Sender: TObject);
begin
  GetQBInfo();
end;

procedure TFQBInfo.btnCloseClick(Sender: TObject);
begin
  Close();
end;

procedure TFQBInfo.GetQBInfo();
// retrieves customer list from server
var
  xdcResponse: TXDataClientResponse;
  QBInfo: TJSObject;
begin
  try
    Utils.ShowSpinner('spinner');
    xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.getQBInfo', []));
    QBInfo := TJSObject(xdcResponse.Result);
    ClientID := String(QBInfo['clientID']);

    if boolean(QBInfo['connected']) then
    begin
      lblCompanyName.Caption := lblCompanyName.Caption + String(QBInfo['CompanyName']);
      lblCompanyID.Caption := lblCompanyID.Caption + String(QBInfo['CompanyID']);
      lblConnected.Caption := 'QuickBooks is connected.';
      lblLastRefresh.Caption := lblLastRefresh.Caption + String(QBInfo['LastRefresh']);
    end
    else
      lblConnected.Caption := 'Quickbooks is not connected.';
    Utils.HideSpinner('spinner');

  except
    on E: EXDataClientRequestException do
    begin
      lblConnected.Caption := 'Quickbooks is not connected.';
      Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
    end;
  end;
end;

procedure TFQBInfo.GetQBLink();
var
  xdcResponse: TXDataClientResponse;
  QBLinkObj: TJSObject;
  QBLink: String;
  qbWindow: TJSWindow;
begin
  try
    xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.getQBLink', []));
    QBLinkObj := TJSObject(xdcResponse.Result);
    QBLink := String(QBLinkObj['value']);
    console.log(QBLinkObj);
    console.log(QBLink);

    qbWindow := window.open('', '_blank');
    if Assigned(qbWindow) then
        qbWindow.location.href := QBLink;
    Close();
  except
    on E: EXDataClientRequestException do
      Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
  end;
end;


end.
