include_guard(GLOBAL)

#[[ Sets 'provider' and 'package' variables in calling scope ]]
function (ixm_fetch_prepare_reference reference)
  string(REGEX MATCH "([^{]+){(.+)}" matched "${reference}")
  if (NOT matched)
    log(FATAL "fetch() called with an incorrect dependency reference '${reference}'")
  endif()
  set(provider ${CMAKE_MATCH_1} PARENT_SCOPE)
  set(package ${CMAKE_MATCH_2} PARENT_SCOPE)
endfunction()

#[[ Gets the 'name' of the package, as this is for pre-invoke stuff ]]
function (ixm_fetch_prepare_name package)
  string(REPLACE "@" ";" result ${package})
  list(GET result 0 resource)
  string(REPLACE "/" ";" result ${resource})
  list(GET result -1 name)
  set(name ${name} PARENT_SCOPE)
endfunction()

#[[ Gets the 'command' for the given provider ]]
function (ixm_fetch_prepare_command provider)
  aspect(GET fetch:${provider} AS command)
  if (NOT command)
    log(FATAL "Could not find global property 'ixm::fetch::${provider}'")
  endif()
  if (NOT COMMAND ${command})
    log(FATAL "global property 'ixm::fetch::${provider}'"
      "does not point to an existing command")
  endif()
  set(command ${command} PARENT_SCOPE)
endfunction()

function (ixm_fetch_prepare_recipe provider recipe)
  set(property-name IXM_FETCH_${provider}_RECIPE)
  set(fallback-name IXM_FETCH_${provider}_DEFAULT)
  get_property(type GLOBAL PROPERTY ${property-name})
  get_property(default GLOBAL PROPERTY ${fallback-name})
  if (NOT type)
    log(FATAL "Could not find global property '${property-name}'")
  endif()
  if (type STREQUAL "ADVANCED")
    ixm_fetch_recipe_advanced(${recipe} "${default}")
  elseif (type STREQUAL "BASIC")
    ixm_fetch_recipe_basic(${recipe} "${default}")
  else ()
    log(FATAL "Unknown recipe type '${type}' for ${property-name}")
  endif()
  set(root ${root} PARENT_SCOPE)
  set(name ${name} PARENT_SCOPE)
  set(tag ${tag} PARENT_SCOPE)
endfunction()

function (ixm_fetch_prepare_dict name)
  dict(KEYS ${name} keys)
  foreach (key IN LISTS keys)
    dict(GET ${name} ${key} value)
    set(${key} ${value} PARENT_SCOPE)
  endforeach()
endfunction()
