# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Wraps the contents of tcl scripts as a cc files.

The rules wrap the tcl scripts in a extern c character array.
"""

def _tcl_encode_impl(ctx):
    """Generates a single C++ file from the provided srcs in a DefaultInfo.
    """
    outfile_name = ctx.attr.out if ctx.attr.out else ctx.attr.name + ".cc"
    output_file = ctx.actions.declare_file(outfile_name)

    (inputs, _) = ctx.resolve_tools(tools = [ctx.attr._tclsh, ctx.attr._encode_script])

    args = ctx.actions.args()
    args.add(ctx.file._encode_script)
    args.add(output_file)
    args.add(ctx.attr.char_array_name)
    args.add_all(ctx.files.srcs)

    ctx.actions.run(
        outputs = [output_file],
        inputs = ctx.files.srcs,
        arguments = [args],
        tools = inputs,
        executable = ([file for file in ctx.files._tclsh if file.basename == "tclsh"][0]),
    )
    return [DefaultInfo(files = depset([output_file]))]

tcl_encode = rule(
    implementation = _tcl_encode_impl,
    attrs = {
        "srcs": attr.label_list(
            allow_empty = False,
            allow_files = [".tcl"],
            doc = "Tcl files to be wrapped.",
        ),
        "char_array_name": attr.string(
            doc = "The name of the extern string array value in the generated file.",
            mandatory = True,
        ),
        "out": attr.string(
            doc = "The name of the C++ source file generated by these rules.",
        ),
        "_encode_script": attr.label(
            default = "@org_theopenroadproject//:src/sta/etc/TclEncode.tcl",
            allow_single_file = True,
        ),
        "_tclsh": attr.label(
            default = "@tk_tcl//:tclsh",
            allow_files = True,
            cfg = "exec",
        ),
    },
)
