components_tasks_FontDownloadTask.bs

import "pkg:/source/api/baserequest.bs"
import "pkg:/source/api/sdk.bs"
import "pkg:/source/utils/misc.bs"

sub init()
  m.top.functionName = "downloadFallbackFont"
end sub

' Downloads fallback font from the server to tmp:/font
sub downloadFallbackFont()
  print "FontDownloadTask: Starting fallback font download..."

  ' Check if server supports fallback fonts
  configEncoding = api.system.GetConfigurationByName("encoding")

  if not isValid(configEncoding) or not isValid(configEncoding.EnableFallbackFont) or not configEncoding.EnableFallbackFont
    print "FontDownloadTask: Server does not support fallback fonts"
    m.top.errorMessage = "Server does not support fallback fonts"
    m.top.fontDownloadSuccess = false
    m.top.fontDownloadCompleted = true
    return
  end if

  ' Get list of available fonts
  re = CreateObject("roRegex", "Name.:.(.*?).,.Size", "s")
  fontReq = APIRequest("FallbackFont/Fonts")

  if not isValid(fontReq)
    print "FontDownloadTask: Failed to create API request for font list"
    m.top.errorMessage = "Failed to create API request for font list"
    m.top.fontDownloadSuccess = false
    m.top.fontDownloadCompleted = true
    return
  end if

  filename = fontReq.GetToString()
  if not isValid(filename)
    print "FontDownloadTask: Failed to get font list from server"
    m.top.errorMessage = "Failed to get font list from server"
    m.top.fontDownloadSuccess = false
    m.top.fontDownloadCompleted = true
    return
  end if

  ' Extract font filename from response
  filename = re.match(filename)
  if not isValid(filename) or filename.count() = 0
    print "FontDownloadTask: Could not parse font filename from server response"
    m.top.errorMessage = "Could not parse font filename from server response"
    m.top.fontDownloadSuccess = false
    m.top.fontDownloadCompleted = true
    return
  end if

  filename = filename[1]
  print "FontDownloadTask: Font filename: " + filename

  ' Download the font file
  fontFileReq = APIRequest("FallbackFont/Fonts/" + filename)
  if not isValid(fontFileReq)
    print "FontDownloadTask: Failed to create API request for font file"
    m.top.errorMessage = "Failed to create API request for font file"
    m.top.fontDownloadSuccess = false
    m.top.fontDownloadCompleted = true
    return
  end if

  ' Download the font file directly to final location
  fontFileReq.gettofile("tmp:/font")

  ' Wait a moment for file to be fully written
  sleep(100)

  ' Verify the file was written successfully
  fs = CreateObject("roFileSystem")
  if not fs.Exists("tmp:/font")
    print "FontDownloadTask: Font file was not created successfully"
    m.top.errorMessage = "Font file was not created successfully"
    m.top.fontDownloadSuccess = false
    m.top.fontDownloadCompleted = true
    return
  end if

  print "FontDownloadTask: Fallback font downloaded successfully"
  m.top.fontDownloadSuccess = true
  m.top.fontDownloadCompleted = true
end sub