#!/usr/bin/python2.7

import sys, re, urllib

# Source File License - MPL 2.0
SOURCE_URL = "https://raw.githubusercontent.com/mozilla/gecko-dev/master/layout/mathml/mathfont.properties"
OUTPUT_FILE = "../../src/mathml_operators.h"

pat = re.compile("^operator.([^.]+).(\w+) = lspace:(\d+) rspace:(\d+)(.*?) # (.*)$")
SEEN_FLAGS = {}
SEEN_OPERATORS = {}

u = urllib.urlopen(SOURCE_URL)
for line in u.readlines():
    line = line.strip()
    if line.startswith("#") or line == "":
        continue;
    mo = pat.match(line)
    if not mo:
        print "ERR %s" % line
    operator, pos, lspace, rspace, flags, comment = mo.groups()
    operator = operator.replace("\\u", "\\x")
    pos = "MATHML_OP_%s" % pos.upper()
    lspace = int(lspace)
    rspace = int(rspace)
    flags = flags.strip().split()
    oflags = []
    for flag in flags:
        if flag.startswith("direction:"):
            flag = flag[10:]
        oflag = "MATHML_OP_%s" % flag.upper()
        oflags.append(oflag)
        SEEN_FLAGS[oflag] = True
    flags = "|".join(oflags)
    if not flags:
        flags = "0"
    oline = """{U"%s", %18s, %d, %d, %s}, // %s""" % (operator, pos, lspace, rspace, flags, comment)
    if not SEEN_OPERATORS.has_key(operator):
        SEEN_OPERATORS[operator] = []
    SEEN_OPERATORS[operator].append(oline)

f = open(OUTPUT_FILE, "w")
f.write("/* Generated by tools/gen_mathml_operators_h.py */\n")
f.write(" * Source file: %s\n" % SOURCE_URL)
f.write(" * License: MPL-2.0\n")
f.write(" */\n")
# The license of the output file must be the same as that of the source.
f.write("\n");
f.write("/*\n");
f.write(" * This Source Code Form is subject to the terms of the Mozilla Public\n");
f.write(" * License, v. 2.0. If a copy of the MPL was not distributed with this\n");
f.write(" * file, You can obtain one at http://mozilla.org/MPL/2.0/.\n");
f.write(" */\n");
f.write("\n");
f.write("// clang-format off\n")
for text, lines in sorted(SEEN_OPERATORS.items()):
    for line in sorted(lines):
        f.write("%s\n" % line)
f.write("// clang-format on\n")
f.close()
for flag in sorted(SEEN_FLAGS):
    print flag
