unit TwitchAPI.Commands.GetUsers.Impl;

interface

uses
  TwitchAPI.Client,
  TwitchAPI.Commands.GetUsers,
  TwitchAPI.Entities;

type

{ TTwitchGetUsersResult }

  TTwitchGetUsersResult = class(TTwitchResult, ITwitchGetUsersResult)
  private
    FUsers: TArray<TTwitchUser>;
  public
    constructor Create;
    function GetUsers: TArray<TTwitchUser>;
    procedure Parse(const AData: string); override;
    property Users: TArray<TTwitchUser> read FUsers;
  end;

{ TTwitchGetUsersCommand }

  TTwitchGetUsersCommand = class(TTwitchCommand, ITwitchGetUsersCommand)
  public
    function Execute: ITwitchGetUsersResult;
    function GetEndpoint: string; override;
    function SetLogin(const AValue: string): ITwitchGetUsersCommand;
  end;

implementation

uses
  System.Generics.Collections,
  System.JSON;

{ TTwitchGetUsersResult }

constructor TTwitchGetUsersResult.Create;
begin
  inherited Create;
  FUsers := [];
end;

function TTwitchGetUsersResult.GetUsers: TArray<TTwitchUser>;
begin
  Result := FUsers;
end;

procedure TTwitchGetUsersResult.Parse(const AData: string);
begin
  var LRoot := TJSONObject.ParseJSONValue(AData);
  try
    var LData := LRoot.GetValue<TJSONArray>('data');
    SetLength(FUsers, LData.Count);
    for var LIndex := 0 to LData.Count - 1 do
    begin
      var LUser := TJSONObject(LData[LIndex]);
      FUsers[LIndex].ID := LUser.GetValue<string>('id');
      FUsers[LIndex].Login := LUser.GetValue<string>('login');
      FUsers[LIndex].DisplayName := LUser.GetValue<string>('display_name');
      FUsers[LIndex].&Type := LUser.GetValue<string>('type');
      FUsers[LIndex].BroadcasterType := LUser.GetValue<string>('broadcaster_type');
      FUsers[LIndex].Description := LUser.GetValue<string>('description');
      FUsers[LIndex].ProfileImageUrl := LUser.GetValue<string>('profile_image_url');
      FUsers[LIndex].OfflineImageUrl := LUser.GetValue<string>('offline_image_url');
      FUsers[LIndex].ViewCount := LUser.GetValue<Integer>('view_count');
      FUsers[LIndex].CreatedAt := LUser.GetValue<TDateTime>('created_at');
    end;
  finally
    LRoot.Free;
  end;
end;

{ TTwitchGetUsersCommand }

function TTwitchGetUsersCommand.Execute: ITwitchGetUsersResult;
begin
  Result := inherited Execute<TTwitchGetUsersResult>();
end;

function TTwitchGetUsersCommand.GetEndpoint: string;
begin
  Result := inherited GetEndpoint + 'users';
end;

function TTwitchGetUsersCommand.SetLogin(const AValue: string): ITwitchGetUsersCommand;
begin
  Query.AddOrSetValue('login', AValue);
  Result := Self;
end;

end.
