unit TwitchAPI.Commands.GetChannelInfo.Impl;

interface

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

type

{ TTwitchGetChannelInfoResult }

  TTwitchGetChannelInfoResult = class(TTwitchResult, ITwitchGetChannelInfoResult)
  private
    FInfos: TArray<TTwitchChannelInfo>;
    FInfo: TTwitchChannelInfo;
  public
    constructor Create;
    function GetInfos: TArray<TTwitchChannelInfo>;
    procedure Parse(const AData: string); override;
    property Info: TTwitchChannelInfo read FInfo;
  end;

{ TTwitchGetChannelInfoCommand }

  TTwitchGetChannelInfoCommand = class(TTwitchCommand, ITwitchGetChannelInfoCommand)
  public
    function Execute: ITwitchGetChannelInfoResult;
    function GetEndpoint: string; override;
    function SetBroadcasterID(const AValue: string): ITwitchGetChannelInfoCommand;
  end;

implementation

uses
  System.Generics.Collections,
  System.JSON,
  System.SysUtils;

{ TTwitchGetChannelInfoResult }

constructor TTwitchGetChannelInfoResult.Create;
begin
  inherited Create;
  FInfos := [];
end;

function TTwitchGetChannelInfoResult.GetInfos: TArray<TTwitchChannelInfo>;
begin
  Result := FInfos;
end;

procedure TTwitchGetChannelInfoResult.Parse(const AData: string);
begin
  var LRoot := TJSONObject.ParseJSONValue(AData);
  try
    var LData := LRoot.GetValue<TJSONArray>('data');
    SetLength(FInfos, LData.Count);
    for var LIndex := 0 to LData.Count - 1 do
    begin
      var LUser := TJSONObject(LData[LIndex]);
      FInfos[LIndex].BroadcasterID := LUser.GetValue<string>('broadcaster_id');
      FInfos[LIndex].BroadcasterLogin := LUser.GetValue<string>('broadcaster_login');
      FInfos[LIndex].BroadcasterName := LUser.GetValue<string>('broadcaster_name');
      FInfos[LIndex].BroadcasterLanguage := LUser.GetValue<string>('broadcaster_language');
      FInfos[LIndex].GameID := LUser.GetValue<string>('game_id');
      FInfos[LIndex].GameName := LUser.GetValue<string>('game_name');
      FInfos[LIndex].Title := LUser.GetValue<string>('title');
      FInfos[LIndex].Delay := LUser.GetValue<Integer>('delay');
      FInfos[LIndex].Tags := LUser.GetValue<TArray<string>>('tags');
      FInfos[LIndex].ContentClassificationLabels := LUser.GetValue<TArray<string>>('content_classification_labels');
      FInfos[LIndex].IsBrandedContent := LUser.GetValue<Boolean>('is_branded_content');
    end;
  finally
    LRoot.Free;
  end;
end;

{ TTwitchGetChannelInfoCommand }

function TTwitchGetChannelInfoCommand.Execute: ITwitchGetChannelInfoResult;
begin
  Result := inherited Execute<TTwitchGetChannelInfoResult>();
end;

function TTwitchGetChannelInfoCommand.GetEndpoint: string;
begin
  Result := inherited GetEndpoint + 'channels';
end;

function TTwitchGetChannelInfoCommand.SetBroadcasterID(
  const AValue: string): ITwitchGetChannelInfoCommand;
begin
  Query.AddOrSetValue('broadcaster_id', AValue);
  Result := Self;
end;

end.
