# Copyright 2010-2021, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""A reas implementation used on Windows platform."""

load("@bazel_skylib//lib:paths.bzl", "paths")
load("@rules_cc//cc/common:cc_common.bzl", "cc_common")
load("@rules_cc//cc/common:cc_info.bzl", "CcInfo")

# "get_winsdk_include_dirs.bzl" is dynamically generated by "windows_sdk_repository.bzl"
load(":get_winsdk_include_dirs.bzl", "get_winsdk_include_dirs")

def _build_win_rc(ctx, resource_name, rc_file, resources, defines, codepage):
    resource_file = ctx.actions.declare_file(resource_name)
    source_dir = ctx.label.package

    includes = [
        rc_file.dirname,
        source_dir,
        ctx.var["BINDIR"],
        ctx.var["GENDIR"],
    ] + get_winsdk_include_dirs() + ["./"]

    transitive_defines = []
    for resource in ctx.attr.resources:
        if CcInfo in resource:
            transitive_defines += resource[CcInfo].compilation_context.defines.to_list()

    copts_defines = [
        copt[2:]
        for copt in ctx.fragments.cpp.copts
        if copt.startswith(("-D", "/D"))
    ]

    arch_defines = ctx.attr.arch_defines

    args = ctx.actions.args()
    args.add_all(
        copts_defines + transitive_defines + defines + ["RC_INVOKED"] + arch_defines,
        format_each = "/D%s",
        uniquify = True,
    )
    args.add_all(includes, format_each = "/I%s", uniquify = True)
    args.add(resource_file, format = "/fo%s")
    if codepage != 1200:  # 1200 is UTF-16
        args.add(codepage, format = "/C%s")
    args.add(rc_file)
    ctx.actions.run(
        inputs = [rc_file] + resources,
        outputs = [resource_file],
        executable = ctx.executable.rc_exe,
        arguments = [args],
        mnemonic = "WindowsRc",
        progress_message = "Compiling resources {0} to {1}".format(
            rc_file.basename,
            resource_file.basename,
        ),
        toolchain = None,
    )

    return resource_file

def _win32_res_rule_impl(ctx):
    rc_files = ctx.files.rc_files
    resources = ctx.files.resources
    manifests = ctx.files.manifests
    defines = ctx.attr.defines
    codepage = ctx.attr.codepage

    resource_files = []
    for rc_file in rc_files:
        resource_files.append(_build_win_rc(
            ctx = ctx,
            resource_name = paths.replace_extension(rc_file.path, ".res"),
            resources = resources,
            rc_file = rc_file,
            defines = defines,
            codepage = codepage,
        ))
    resource_file_provider = DefaultInfo(files = depset(resource_files))

    resource_link_flags = [res.path for res in resource_files]

    manifest_flags = []
    if len(manifests) > 0:
        manifest_flags.append("/MANIFEST:EMBED")
        for manifest in manifests:
            manifest_flags.append("/MANIFESTINPUT:{}".format(manifest.path))

    linker_input = cc_common.create_linker_input(
        owner = ctx.label,
        additional_inputs = depset(resource_files + manifests),
        user_link_flags = depset(resource_link_flags + manifest_flags),
    )
    linking_context = cc_common.create_linking_context(
        linker_inputs = depset([linker_input]),
    )
    return [
        resource_file_provider,
        CcInfo(linking_context = linking_context),
    ]

_win32_res_rule = rule(
    _win32_res_rule_impl,
    attrs = {
        "rc_files": attr.label_list(
            allow_files = [".rc"],
        ),
        "resources": attr.label_list(
            allow_files = True,
        ),
        "manifests": attr.label_list(
            allow_files = [".manifest"],
        ),
        "defines": attr.string_list(
            allow_empty = True,
            default = [],
            mandatory = False,
        ),
        "codepage": attr.int(
            default = 1200,  # UTF-16
            mandatory = False,
        ),
        "rc_exe": attr.label(
            executable = True,
            cfg = "exec",
            allow_single_file = [".exe"],
            default = Label(":bin/rc.exe"),
        ),
        "arch_defines": attr.string_list(
            default = [],
            mandatory = False,
        ),
    },
    provides = [CcInfo],
    fragments = ["cpp"],
)

def windows_resource(name, **kwargs):
    _win32_res_rule(
        name = name,
        arch_defines = select({
            "@platforms//cpu:arm64": ["_ARM64_", "_WIN64"],
            "@platforms//cpu:x86_64": ["_AMD64_", "_WIN64"],
            "@platforms//cpu:x86_32": ["_X86_"],
            "//conditions:default": [""],
        }),
        **kwargs
    )
