unit View.UserProfile;

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, WEBLib.ExtCtrls, DB, XData.Web.JsonDataset,
  XData.Web.Dataset, XData.Web.Connection, Vcl.Forms, ConnectionModule;

type
  TFViewUserProfile = class(TWebForm)
    WebLabel1: TWebLabel;
    WebLabel3: TWebLabel;
    edtUsername: TWebEdit;
    WebLabel2: TWebLabel;
    edtUserId: TWebEdit;
    edtFullName: TWebEdit;
    WebLabel4: TWebLabel;
    edtPhone: TWebEdit;
    WebLabel5: TWebLabel;
    chkAdminUser: TWebCheckBox;
    edtEmail: TWebEdit;
    WebLabel6: TWebLabel;
    btnConfirm: TWebButton;
    lblResult: TWebLabel;
    XDataWebClient1: TXDataWebClient;
    WebButton1: TWebButton;
    pnlMessage: TWebPanel;
    lblMessage: TWebLabel;
    btnCloseNotification: TWebButton;
    procedure WebFormShow(Sender: TObject);
    procedure btnConfirmClick(Sender: TObject);
    [async] procedure EditUser();
    [async] procedure GetUser();
    procedure WebButton1Click(Sender: TObject);
    procedure HideNotification();
    procedure ShowNotification(Notification: string);
    procedure btnCloseNotificationClick(Sender: TObject);
    function CheckInputs(): boolean;
  end;

var
  FViewUserProfile: TFViewUserProfile;

implementation

uses
  Auth.Service,
  XData.Model.Classes;

{$R *.dfm}

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

procedure TFViewUserProfile.btnConfirmClick(Sender: TObject);
var
  resultString: string;
begin
  asm
    var messageDiv = document.getElementById('view.login.message');
    messageDiv.classList.remove('alert-success');
    messageDiv.classList.add('alert-danger');
  end;
  if CheckInputs() then
  begin
    EditUser();
  end
end;

procedure TFViewUserProfile.EditUser();
var
  xdcResponse: TXDataClientResponse;
  responseString: TJSObject;
  editOptions: string;
begin
  if(checkInputs()) then
  begin
    console.log(edtFullName.Text);
    editOptions := '&username=' + edtUsername.Text +
                  '&fullname=' + edtFullName.Text +
                  '&phonenumber=' + edtPhone.Text +
                  '&email=' + edtEmail.Text;

    xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.EditUser',
        [editOptions]));
    responseString :=  TJSObject(xdcResponse.Result);
      asm
        var messageDiv = document.getElementById('view.login.message');
        messageDiv.classList.remove('alert-danger');
        messageDiv.classList.add('alert-success');
    end;
    ShowNotification(string(responseString['value']));
  end;
end;

procedure TFViewUserProfile.WebButton1Click(Sender: TObject);
var
  xdcResponse: TXDataClientResponse;
  userList: TJSObject;
  data: TJSArray;
  user: TJSObject;
begin
  GetUser();
  showNotification('Failure:Changes discarded');
end;

procedure TFViewUserProfile.WebFormShow(Sender: TObject);
var
  xdcResponse: TXDataClientResponse;
  userList: TJSObject;
  data: TJSArray;
  user: TJSObject;
begin
  HideNotification;
  GetUser();

  //edtJwt.Text := TJSJSON.stringify(AuthService.TokenPayload);
  chkAdminUser.Checked := JS.toBoolean(AuthService.TokenPayload.Properties['user_admin']);
end;

procedure TFViewUserProfile.GetUser;
var
  xdcResponse: TXDataClientResponse;
  userList: TJSObject;
  data: TJSArray;
  user: TJSObject;
begin
  xdcResponse := await(XDataWebClient1.RawInvokeAsync('ILookupService.GetUsers',
        [JS.toString(AuthService.TokenPayload.Properties['user_name'])]));
  userList :=  TJSObject(xdcResponse.Result);
  data := TJSArray(userList['data']);
  user := TJSObject(data[0]);
  edtUsername.Text := string(user['username']);
  edtFullName.Text := string(user['full_name']);
  edtPhone.Text := string(user['phone_number']);
  edtEmail.Text := string(user['email_address']);
  edtUserId.Text := string(user['userID']);
  chkAdminUser.Checked := boolean(user['admin']);
end;

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

procedure TFViewUserProfile.ShowNotification(Notification: string);
var
  splitNotification: TArray<string>;
begin
  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;
    lblMessage.Caption := splitNotification[1];
    pnlMessage.ElementHandle.hidden := False;
  end;
end;

function TFViewUserProfile.CheckInputs(): boolean;
  var
  checkString: string;
  charIndex: integer;
  phoneNum: string;
begin
  Result := false;
  checkString := edtFullName.Text + edtUsername.Text + edtPhone.Text + edtEmail.Text;
  if string(edtFullName.Text).IsEmpty then
  begin
    ShowNotification('Failure:Full Name field is blank!');
    exit;
  end;

  if string(edtUsername.Text).IsEmpty then
  begin
    ShowNotification('Failure:Username field is blank!');
    exit;
  end;

  if string(edtPhone.Text).IsEmpty then
  begin
    ShowNotification('Failure:Phone Number field is blank!');
    exit;
  end;

  if string(edtEmail.Text).IsEmpty then
  begin
    ShowNotification('Failure:Email field is blank!');
    exit;
  end;

  if checkString.Contains('&') then
  begin
    ShowNotification('Failure:No fields may contain "&&"!');
    exit;
  end;

  if string(edtEmail.Text).Contains('@') = false then
  begin
    ShowNotification('Failure:Please enter a valid email address');
    exit;
  end;

  if (length(string(edtEmail.Text).Split(['@'])) <> 2) or (string(edtEmail.text).CountChar('@') > 1) then
  begin
    ShowNotification('Failure:Please enter a valid email address');
    exit;
  end;

  phoneNum := edtPhone.Text;

  if (not phoneNum.Contains('(')) or (not phoneNum.Contains(')')) or (not phoneNum.Contains('-')) then
  begin
    ShowNotification('Failure:Please enter a valid phone number');
    exit;
  end;

  if (phoneNum.CountChar('(') <> 1) or (phoneNum.CountChar(')') <> 1) or (phoneNum.CountChar('-') <> 1) or (phoneNum.CountChar(' ') > 1) then
  begin
    ShowNotification('Failure:Please enter a valid phone number');
    exit;
  end;

  phoneNum := phoneNum.Replace('(', '');
  phoneNum := phoneNum.Replace(')', '');
  phoneNum := phoneNum.Replace('-', '');
  phoneNum := phoneNum.Replace(' ', '');
  console.log(phoneNum);
  console.log(length(phoneNum));

  if(length(phoneNum) <> 10) then
  begin
    ShowNotification('Failure:Please enter a valid phone number');
    exit;
  end;

  for CharIndex := 1 to Length(phoneNum) do
  begin
    if not (phoneNum[CharIndex] in ['0' .. '9']) then
    begin
      console.log('here');
      ShowNotification('Failure:Please enter a valid phone number');
      exit;
    end;
  end;
  result := true;
end;

end.
