import("//Meta/gn/build/compiled_action.gni")
import("//Meta/gn/build/download_cache.gni")
import("//Meta/gn/build/download_file.gni")
import("//Meta/gn/build/extract_archive_contents.gni")

declare_args() {
  # If true, Download tzdata from data.iana.org and use it in LibTimeZone
  # Data will be downloaded to $cache_path/TZDB
  enable_timezone_database_download = true
}

tzdb_cache = cache_path + "TZDB/"

if (enable_timezone_database_download) {
  download_file("timezone_database_download") {
    version = "2023c"
    url =
        "https://data.iana.org/time-zones/releases/tzdata" + version + ".tar.gz"
    cache = tzdb_cache
    output = "tzdb.tar.gz"
    version_file = "version.txt"
  }
  extract_archive_contents("timezone_database_files") {
    deps = [ ":timezone_database_download" ]
    archive = get_target_outputs(":timezone_database_download")
    directory = tzdb_cache

    # NOSORT
    files = [
      "zone1970.tab",
      "africa",
      "antarctica",
      "asia",
      "australasia",
      "backward",
      "etcetera",
      "europe",
      "northamerica",
      "southamerica",
    ]
  }
  compiled_action("generate_timezone_sources") {
    tool = "//Meta/Lagom/Tools/CodeGenerators/LibTimeZone:GenerateTimeZoneData"
    deps = [ ":timezone_database_files" ]
    inputs = get_target_outputs(":timezone_database_files")
    outputs = [
      "$target_gen_dir/TimeZoneData.h",
      "$target_gen_dir/TimeZoneData.cpp",
    ]
    args = [
      "-h",
      rebase_path(outputs[0], root_build_dir),
      "-c",
      rebase_path(outputs[1], root_build_dir),
      "-z",

      # NOTE: Coordinates file must be inputs[0]
    ]
    foreach(data_file, inputs) {
      args += [ rebase_path(data_file, root_build_dir) ]
    }
  }
}

source_set("LibTimeZone") {
  output_name = "timezone"
  include_dirs = [
    "//Userland/Libraries",
    "$target_gen_dir/..",
  ]
  sources = [
    "Forward.h",
    "TimeZone.cpp",
    "TimeZone.h",
  ]
  deps = [
    "//AK",
    "//Userland/Libraries/LibCore",
  ]
  if (enable_timezone_database_download) {
    deps += [ ":generate_timezone_sources" ]
    sources += get_target_outputs(":generate_timezone_sources")
  }
}
