{ 
  Map Viewer Download Engine Free Pascal Tile-File-Reader.
  Copyright (c) 2023 Ekkehard Domning, ekkehard@domning.eu.
  Extends 
  
  Map Viewer Download Engine Free Pascal HTTP Client
  Copyright (C) 2011 Maciej Kaczkowski / keit.co

  License: modified LGPL with linking exception (like RTL, FCL and LCL)

  See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution,
  for details about the license.

  See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL

  Taken from:
  https://forum.lazarus.freepascal.org/index.php/topic,12674.msg160255.html#msg160255
}

unit mvDLEFpcTFR;

{$mode objfpc}{$H+}

{.$DEFINE LOG_URL}

interface

uses
  SysUtils, Classes,
  mvDLEFpc;

type

  { TMVDLEFFPCTFR }
  // Purpose is to allow the read of tile files from the local storage
  // instead of fetching the tiles from the internet.
  // The URL must follow the scheme for file reading and has to start with "FILE:///"
  // instead of "http://" or "https://".
  // The remaining FilePath must point to the desired Tile-File.
  // If the scheme ist not as exprected, then the inherited method is called

  TMVDLEFFPCTFR = class(TMVDEFPC)
  public
    procedure DownloadFile(const Url: string; AStream: TStream); override;
  published
  end;


implementation

{$IFDEF LOG_URL}
uses
  lazlogger;
{$ENDIF}

{ TMVDLEFFPCTFR }

procedure TMVDLEFFPCTFR.DownloadFile(const Url: string; AStream: TStream);
const
  FILE_SCHEME : String = 'FILE:///';
var
  fs : TFileStream;
  fn : String;
  s : String;
begin
  s := UpperCase(Copy(Url,1,Length(FILE_SCHEME)));
  if s <> FILE_SCHEME then
  begin // The URL-Scheme is not file, try the default loading stuff
    inherited;
    Exit;
  end;
  {$IFDEF LOG_URL}
  DebugLn(Url);
  {$ENDIF}
  fn := Copy(Url,Length(FILE_SCHEME)+1,MaxInt);   // Extract the file-path
  if not FileExists(fn) then Exit; // If the file does not exists, exit
  fs := Nil;
  try
    try
      fs := TFileStream.Create(fn,fmOpenRead); //Open the Tile-File
      AStream.CopyFrom(fs,fs.Size); //Copy the contentn into the strem
      AStream.Position := 0;
    except
    end;	
  finally
    if Assigned(fs) then
      fs.Free;
  end;
end;

end.
