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();
  public
    { Public declarations }
  end;

var
  FQBInfo: TFQBInfo;

implementation

{$R *.dfm}

uses View.Main, Utils;

procedure TFQBInfo.btnLinkToQBClick(Sender: TObject);
var
  qblink, redirectUri: string;
  qbWindow: TJSWindow;
begin
  qblink := 'https://appcenter.intuit.com/connect/oauth2';
  qblink := qblink + '?client_id=' + ClientID;
  qblink := qblink + '&response_type=code';
  qblink := qblink + '&scope=com.intuit.quickbooks.accounting';
  qblink := qblink + '&state=7';
  redirectUri := DMConnection.AuthConnection.URL + 'AuthService/QBAuthorize';
  qblink := qblink + '&redirect_uri=' + RedirectUri;
  console.log(redirectUri);
  console.log(qbLink);
  qbWindow := window.open('', '_blank');
  if Assigned(qbWindow) then
      qbWindow.location.href := qbLink;
  Close();
end;

procedure TFQBInfo.WebFormCreate(Sender: TObject);
begin
  if not DMConnection.ApiConnection.Connected then
   begin
    DMConnection.ApiConnection.OpenAsync;
    console.log('report requirements connection open')
   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']);
    console.log(QBInfo);
    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
      Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
  end;
end;


end.
