//******************************************************************************
// LAYERS parameter: config_a_b_c
//    a = 1 for depth in meters, 2 for depth in feet, 3 for fathoms
//    b = 1 for 1 m safety depth (beginning of blue coloring) (unit equal to that set by a)
//    c = 0 for pristine Navionics charts, 1 for Sonar Charts
//
// TRANSPARENT parameter: 
//    FALSE for non-layer
//    TRUE for layer
//    
//******************************************************************************

const
  cReqParams = 'LAYERS=config_1_1_0&TRANSPARENT=FALSE&theme=0';

//******************************************************************************

const
  cTTL = 24*60*60; // 24 hour
  
function CheckTTL(const ATimeStamp: Integer): Boolean;
begin
  Result := (cTTL div 2) > GetUnixTime - ATimeStamp;
end;

function GetNavToken: AnsiString;
var
  VNavToken: AnsiString;
  VTimeStamp: Integer; 
  VResponseCode: Cardinal;
  VResponseHeader, VResponseData: AnsiString;
  VRequestUrl, VRequestHeader: AnsiString;
begin
  Result := '';
  
  Global.Lock;
  try
    if Global.Exists(0) and Global.Exists(1) then begin
      VNavToken := Global.GetVar(0);
      VTimeStamp := Global.GetVar(1);
      if (VNavToken <> '') and (VTimeStamp <> 0) and CheckTTL(VTimeStamp) then begin
        Result := VNavToken;
      end; 
    end;
    
    if (Result = '') and Assigned(Downloader) then begin          
      VRequestUrl := 'https://tile1.navionics.com/tile/get_key/Navionics_webapi_04041/maps.garmin.com';
      VRequestHeader := 'Origin: https://maps.garmin.com' + #13#10 + 'Referer: https://maps.garmin.com/';
      VResponseHeader := '';
      VResponseData := ''; 
      VResponseCode := Downloader.DoHttpRequest(VRequestUrl, VRequestHeader, '', VResponseHeader, VResponseData);
   
      if VResponseCode = 200 then begin
        Result := VResponseData;
        Global.SetVar(0, Result);
        Global.SetVar(1, GetUnixTime);
      end; 
    end;
  finally
    Global.Unlock;
  end;
end;

//******************************************************************************

var
  VNavToken: AnsiString;
begin
  VNavToken := GetNavToken;
  if VNavToken <> '' then begin
    ResultURL := TemplateToUrl(GetURLBase) + '?' + cReqParams + '&' + 'navtoken=' + VNavToken;
  end else begin
    ResultURL := '';
  end;
end.
