unit untDownloadImage;

interface

uses
  Classes, SysUtils, System.Net.HttpClientComponent, System.Net.URLClient,
  System.Net.HttpClient, FMX.Objects;

const
  RETRY_TIMES = 5;

type
  TDownloader = class
  public
    class function DownloadFile(AUrl: string; ASavePath: string): Boolean;
    class function DownloadCardImage(ACArdId: Int64): Boolean;
    class procedure LoadCardImage(ACArdId: Int64; AImg: TImage);
  end;

implementation

{ TDownloader }

class function TDownloader.DownloadCardImage(ACArdId: Int64): Boolean;
var
  AFileName: string;
  AUrl: string;
  ATry: Integer;
  ARet: Boolean;
begin
  ATry := 0;
  ARet := False;
  Aurl := Format('https://cdn.233.momobako.com/ygopro/pics/%d.jpg!half', [ACardId]);
  AFileName:= ExtractFilePath(ParamStr(0)) + PathDelim + 'cardimg' + PathDelim + Format('%d.jpg', [ACardId]);
  while (ATry < RETRY_TIMES) do begin
    ARet := DownloadFile(AUrl, AFileName);
    if (ARet) then Break;
    Inc(ATry);
  end;
  if (not ARet) then begin
    DeleteFile(AFileName);
  end;
  Exit(ARet);
end;

class function TDownloader.DownloadFile(AUrl, ASavePath: string): Boolean;
var
  http: TNetHTTPClient;
  resp: IHTTPResponse;
  ms: TMemoryStream;
begin
  Result := False;
  http:= TNetHTTPClient.Create(nil);
  http.Asynchronous := False;
  ms:= TMemoryStream.Create;
  try
    resp := http.Get(AUrl, ms);
    if resp.StatusCode = 200 then begin
       ms.SaveToFile(ASavePath);
       Result := True;
    end;
  except

  end;
  ms.Free;
  http.Free;
end;

class procedure TDownloader.LoadCardImage(ACArdId: Int64; AImg: TImage);
var
  AFileName: string;
begin
  AFileName:= ExtractFilePath(ParamStr(0)) + PathDelim + 'cardimg' + PathDelim + Format('%d.jpg', [ACardId]);
  if (ACardId > 0) and (FileExists(AFileName)) then begin
    AImg.Bitmap.LoadFromFile(AFileName);
  end;
end;

end.
