load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "copy_to_bin")
load("@aspect_rules_esbuild//esbuild:defs.bzl", "esbuild")
load("@aspect_rules_js//js:defs.bzl", "js_library")
load("@aspect_rules_ts//ts:defs.bzl", "ts_project")
load("@npm//:defs.bzl", "npm_link_all_packages")
load("@rules_pkg//pkg:zip.bzl", "pkg_zip")
load("//java:defs.bzl", "merge_jars")

npm_link_all_packages(name = "node_modules")

js_library(
    name = "esbuild-base-config",
    srcs = [
        "esbuild.base.config.mjs",
    ],
)

js_library(
    name = "esbuild-bazel-config",
    srcs = [
        "esbuild.bazel.config.mjs",
    ],
    deps = [
        ":esbuild-base-config",
    ],
)

SRCS = glob(
    [
        "public/**/*",
        "src/**/*",
    ],
    exclude = [
        "src/simple.ts",
        "src/**/*.test.tsx",
    ],
)

DEPS = [
    ":node_modules/@apollo/client",
    ":node_modules/@mui/icons-material",
    ":node_modules/@mui/material",
    ":node_modules/@novnc/novnc",
    ":node_modules/@types/node",
    ":node_modules/graphql.macro",
    ":node_modules/pretty-ms",
    ":node_modules/react",
    ":node_modules/react-dom",
    ":node_modules/react-modal",
    ":node_modules/react-router-dom",
]

ts_project(
    name = "transpile_ts",
    srcs = SRCS,
    allow_js = True,
    assets = glob(["src/assets/**/*"]),
    resolve_json_module = True,
    tsconfig = "tsconfig.json",
    deps = DEPS,
)

esbuild(
    name = "bundle",
    srcs = [
        "esbuild.base.config.mjs",
        "esbuild.bazel.config.mjs",
        ":package.json",
    ] + DEPS + SRCS,
    # We disable the sandbox because it makes the build incredibly long.
    # This is okay because our CI builds use an RBE
    bazel_sandbox_plugin = False,
    bundle = True,
    config = ":esbuild-bazel-config",
    entry_point = "src/index.tsx",
    external = [
        "fs",
        "module",
        "os",
        "path",
        "util",
    ],
    format = "iife",
    minify = True,
    output_dir = True,
    platform = "browser",
    sourcemap = "inline",
    target = "es6",
)

copy_to_bin(
    name = "package_json",
    srcs = ["package.json"],
    visibility = ["//visibility:public"],
)

copy_to_bin(
    name = "tsconfig",
    srcs = ["tsconfig.json"],
    visibility = ["//javascript/grid-ui:__subpackages__"],
)

pkg_zip(
    name = "react-zip",
    srcs = [
        ":bundle",
    ],
    out = "react-zip.jar",
    package_dir = "grid-ui",
    strip_prefix = "bundle",
)

merge_jars(
    name = "add-missing-dirs",
    inputs = [
        ":react-zip",
        "//javascript/grid-ui/public",
    ],
)

java_import(
    name = "react_jar",
    jars = [":add-missing-dirs"],
    visibility = [
        "//java/src/org/openqa/selenium/grid:__pkg__",
    ],
)
