unit AddCustomer;

interface

uses
  System.SysUtils, System.Generics.Collections, System.Classes, JS, Web, WEBLib.Graphics, WEBLib.Controls,
  WEBLib.Forms, WEBLib.Dialogs, WEBLib.Menus, WEBLib.ExtCtrls, WEBLib.StdCtrls,
  WEBLib.JSON, Auth.Service, XData.Web.Client, WebLib.Storage,
  ConnectionModule, App.Types, Vcl.StdCtrls, Vcl.Controls, WEBLib.DBCtrls,
  Data.DB, XData.Web.JsonDataset, XData.Web.Dataset, WEBLib.DB, WEBLib.Grids;

type
  TFViewAddCustomer = class(TWebForm)
    dtpStartDate: TWebDateTimePicker;
    dtpEndDate: TWebDateTimePicker;
    edtShortName: TWebDBEdit;
    edtName: TWebDBEdit;
    edtBillAddress: TWebDBEdit;
    edtBillCity: TWebDBEdit;
    edtBillState: TWebDBEdit;
    edtBillZip: TWebDBEdit;
    edtBillContact: TWebDBEdit;
    edtPhone: TWebDBEdit;
    edtFax: TWebDBEdit;
    edtRep: TWebDBEdit;
    btnSave: TWebButton;
    btnCancel: TWebButton;
    btnDelete: TWebButton;
    btnClose: TWebButton;
    btnEdit: TWebButton;
    pnlMessage: TWebPanel;
    lblMessage: TWebLabel;
    btnCloseNotification: TWebButton;
    XDataWebClient1: TXDataWebClient;
    WebDataSource1: TWebDataSource;
    XDataWebDataSet1: TXDataWebDataSet;
    XDataWebDataSet1SHORT_NAME: TStringField;
    XDataWebDataSet1NAME: TStringField;
    XDataWebDataSet1BILL_ADDRESS: TStringField;
    XDataWebDataSet1BILL_CITY: TStringField;
    edtCustomerID: TWebDBEdit;
    edtQBID: TWebDBEdit;
    wdbtcAddresses: TWebDBTableControl;
    wdsShipTo: TWebDataSource;
    xdwdsShipTo: TXDataWebDataSet;
    xdwdsShipToADDRESS: TStringField;
    XDataWebDataSet1BILL_STATE: TStringField;
    XDataWebDataSet1BILL_CONTACT: TStringField;
    XDataWebDataSet1BILL_ZIP: TStringField;
    XDataWebDataSet1START_DATE: TStringField;
    XDataWebDataSet1END_DATE: TStringField;
    XDataWebDataSet1QB_LIST_ID: TStringField;
    XDataWebDataSet1FAX: TStringField;
    XDataWebDataSet1PHONE: TStringField;
    XDataWebDataSet1REP_USER_ID: TIntegerField;
    XDataWebDataSet1CUSTOMER_ID: TIntegerField;
    procedure WebFormShow(Sender: TObject);
    procedure btnCloseNotificationClick(Sender: TObject);
    procedure btnSaveClick(Sender: TObject);
  private
    { Private declarations }

    procedure HideNotification();
    procedure ShowNotification(Notification: string);
    [async] procedure GetCustomer();
    [async] procedure SendCustomerToServer();
  var
    customerID: string;
    notification: string;
    mode: string;
  public
    { Public declarations }
     class function CreateForm(AElementID, customerInfo, info: string): TWebForm;
  end;

var
  FViewAddCustomer: TFViewAddCustomer;

implementation

{$R *.dfm}

uses View.Main;

procedure TFViewAddCustomer.btnCloseNotificationClick(Sender: TObject);
begin
  HideNotification();
end;

procedure TFViewAddCustomer.SendCustomerToServer();
var
  customerJSON: TJSONObject;
  Field: TField;
  Response: TXDataClientResponse;
  notification: TJSObject;
begin

  customerJSON := TJSONObject.Create;

  if dtpStartDate.Date <> 0 then
    XDataWebDataSet1START_DATE.Value := DateTimeToStr(dtpStartDate.Date);

  if dtpEndDate.Date <> 0 then
    XDataWebDataSet1END_DATE.Value := DateTimeToStr(dtpEndDate.Date);

  XDataWebDataSet1.First;

  while not XDataWebDataSet1.Eof do
  begin
    for Field in XDataWebDataSet1.Fields do
    begin
      if Field is TStringField then
      begin
        if Field.AsString = '' then
          customerJSON.AddPair(Field.FieldName, '')
        else
          customerJSON.AddPair(Field.FieldName, Field.AsString);  // Add all other fields
      end
      else if Field is TIntegerField then
      begin
        customerJSON.AddPair(Field.FieldName, Field.AsString);
      end;
    end;
    XDataWebDataSet1.Next;
  end;

  customerJSON.AddPair('mode', mode);
  if mode = 'EDIT' then
    customerJSON.AddPair('CUSTOMER_ID', customerID);

  Response := await(XDataWebClient1.RawInvokeAsync('ILookupService.AddCustomer',
              [customerJSON.ToString]));

  notification := TJSObject(Response.Result);
  ShowNotification(string(notification['status']));
  console.log(notification['status']);

end;

procedure TFViewAddCustomer.btnSaveClick(Sender: TObject);
begin
  sendCustomerToServer();
end;

class function TFViewAddCustomer.CreateForm(AElementID: string; customerInfo: string; info: string): TWebForm;
begin
  Application.CreateForm(TFViewAddCustomer, AElementID, Result,
    procedure(AForm: TObject)
    begin
      with TFViewAddCustomer(AForm) do
      begin
        TFViewAddCustomer(AForm).customerID := customerInfo;
        TFViewAddCustomer(AForm).notification := info;
      end;
    end
  );

end;

procedure TFViewAddCustomer.GetCustomer;
var
  xdcResponse: TXDataClientResponse;
  customer : TJSObject;
  address: string;
  items: TJSObject;
begin
  if CustomerID = '' then
  begin
    console.log(CustomerID);
    customerID := '-1';
    mode := 'ADD';
  end
  else
    mode := 'EDIT';
  xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.GetCustomer',
        [customerID]));
  customer :=  TJSObject(xdcResponse.Result);
  XDataWebDataSet1.Close;
  XDataWebDataSet1.SetJsonData(customer);
  XDataWebDataSet1.Open;

  if CustomerID = '-1' then
  begin
    edtCustomerID.Text := '';
  end;

  if XDataWebDataSet1.FieldByName('START_DATE').AsString <> '' then
    dtpStartDate.Date := XDataWebDataSet1.FieldByName('START_DATE').AsDateTime;

  if XDataWebDataSet1.FieldByName('END_DATE').AsString <> '' then
    dtpEndDate.Date := XDataWebDataSet1.FieldByName('End_DATE').AsDateTime;

  xdwdsShipTo.Close;
  xdwdsShipTo.SetJSONData(customer['ADDRESS_LIST']);
  xdwdsShipTo.Open;

  {xdwdsQBItem.Close;
  items := TJSObject(customer['ITEMS']);
  xdwdsQBItem.SetJsonData(items['data']);
  xdwdsQBITEM.Open;}

end;

procedure TFViewAddCustomer.WebFormShow(Sender: TObject);
var
  SQL: string;
begin
  if notification = '' then
    hideNotification();

  getCustomer();

  dtpStartDate.Date := 0;
  dtpEndDate.Date := 0;
end;

procedure TFViewAddCustomer.HideNotification;
begin
  pnlMessage.ElementHandle.hidden := True;
end;

procedure TFViewAddCustomer.ShowNotification(Notification: string);
var
  splitNotification: TArray<string>;
begin
  console.log(notification);
  if Notification <> '' then
  begin
    splitNotification := Notification.Split([':']);
    if(splitNotification[0] = 'Success') then
    begin
      asm
        var messageDiv = document.getElementById('view.login.message');
        messageDiv.classList.remove('alert-danger');
        messageDiv.classList.add('alert-success');
      end;
    end
    else
    begin
      asm
        var messageDiv = document.getElementById('view.login.message');
        messageDiv.classList.remove('alert-success');
        messageDiv.classList.add('alert-danger');
      end;
    end;
    console.log(splitNotification[1]) ;
    lblMessage.Caption := splitNotification[1];
    pnlMessage.ElementHandle.hidden := False;
  end;
end;

end.