# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import buildconfig
import mozpack.path as mozpath
import os
import runpy
import subprocess
import string
import sys

SERVO_BASE = mozpath.join(buildconfig.topsrcdir, "servo")
SERVO_PROP_BASE = mozpath.join(SERVO_BASE, "components", "style", "properties")


def generate_data(output, template):
    output.write("# THIS IS AN AUTOGENERATED FILE.  DO NOT EDIT\n\n")
    output.write(
        subprocess.check_output(
            [
                sys.executable,
                mozpath.join(SERVO_PROP_BASE, "build.py"),
                "gecko",
                "geckolib",
                template,
            ],
            universal_newlines=True,
        )
    )

    # Add all relevant files into the dependencies of the generated file.
    DEP_EXTS = [".py", ".rs", ".zip"]
    deps = set()
    for path, dirs, files in os.walk(SERVO_PROP_BASE):
        for file in files:
            if os.path.splitext(file)[1] in DEP_EXTS:
                deps.add(mozpath.join(path, file))
    return deps


def generate_header(output, data):
    data = runpy.run_path(data)["data"]

    output.write(
        """/* THIS IS AN AUTOGENERATED FILE.  DO NOT EDIT */

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

#define CSS_PROP_DOMPROP_PREFIXED(name_) \\
  CSS_PROP_PUBLIC_OR_PRIVATE(Moz ## name_, name_)

#ifndef CSS_PROP_LONGHAND
#define CSS_PROP_LONGHAND(name_, id_, method_, flags_, pref_) /* nothing */
#define DEFINED_CSS_PROP_LONGHAND
#endif

#ifndef CSS_PROP_SHORTHAND
#define CSS_PROP_SHORTHAND(name_, id_, method_, flags_, pref_) /* nothing */
#define DEFINED_CSS_PROP_SHORTHAND
#endif

#ifndef CSS_PROP_ALIAS
#define CSS_PROP_ALIAS(name_, aliasid_, id_, method_, flags_, pref_) /* nothing */
#define DEFINED_CSS_PROP_ALIAS
#endif

"""
    )

    # Some flags are only used for code generation, so we don't need to
    # expose them to runtime.
    COMPILE_TIME_FLAGS = {"ExposedOnGetCS"}

    MACRO_NAMES = {
        "longhand": "CSS_PROP_LONGHAND",
        "shorthand": "CSS_PROP_SHORTHAND",
        "alias": "CSS_PROP_ALIAS",
    }
    for prop in data.values():
        is_internal = "Internal" in prop.flags
        flags = " | ".join(
            "CSSPropFlags::{}".format(flag)
            for flag in prop.flags
            if flag not in COMPILE_TIME_FLAGS
        )
        if not flags:
            flags = "CSSPropFlags(0)"
        pref = '"' + prop.pref + '"'
        method = prop.method
        if prop.type() == "alias":
            params = [prop.name, prop.alias_id, prop.prop_id, method, flags, pref]
        else:
            if method == "CssFloat":
                method = "CSS_PROP_PUBLIC_OR_PRIVATE(CssFloat, Float)"
            elif method.startswith("Moz"):
                method = "CSS_PROP_DOMPROP_PREFIXED({})".format(method[3:])
            params = [prop.name, prop.id, method, flags, pref]
        excludes = []
        if is_internal:
            excludes.append("CSS_PROP_LIST_EXCLUDE_INTERNAL")
        if "Style" not in prop.rules:
            excludes.append("CSS_PROP_LIST_EXCLUDE_NOT_IN_STYLE")

        if excludes:
            output.write(
                "#if {}\n".format(
                    " || ".join("!defined " + exclude for exclude in excludes)
                )
            )
        output.write("{}({})\n".format(MACRO_NAMES[prop.type()], ", ".join(params)))
        if excludes:
            output.write("#endif\n")

    output.write(
        """
#ifdef DEFINED_CSS_PROP_ALIAS
#undef CSS_PROP_ALIAS
#undef DEFINED_CSS_PROP_ALIAS
#endif

#ifdef DEFINED_CSS_PROP_SHORTHAND
#undef CSS_PROP_SHORTHAND
#undef DEFINED_CSS_PROP_SHORTHAND
#endif

#ifdef DEFINED_CSS_PROP_LONGHAND
#undef CSS_PROP_LONGHAND
#undef DEFINED_CSS_PROP_LONGHAND
#endif

#undef CSS_PROP_DOMPROP_PREFIXED
"""
    )
