#!/usr/bin/env python

import datetime
import json
import logging
import logging.config
import os
import re
import shutil

import database
import haxerenderer

current_dir = os.path.dirname(__file__)
root_dir = os.path.join(current_dir, "..")

logging.config.fileConfig(os.path.join(current_dir, "logging.conf"))
_logger = logging.getLogger("generate-haxe")

header = """/*
 * Copyright (C)2005-%s Haxe Foundation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

// This file is generated, do not edit!
""" % (datetime.date.today().year)

db = database.Database(os.path.join(root_dir, "database"))
db.LoadFromCache()

generated_dir = "generated"
shutil.rmtree(os.path.join(root_dir, generated_dir), ignore_errors=True)

with open("mdn-js.json") as f:
    mdn_js = json.load(f)

    classes_by_src = {}
    for name in mdn_js:
        doc = mdn_js[name]
        classes_by_src[doc["srcUrl"]] = "/".join(haxerenderer.to_haxe(name))

    # Replace internal links so they point to the Haxe API doc, if available
    def replace_href (m):
        href = m.group(1)
        if href in classes_by_src:
            return "href=\"/api/%s\"" % classes_by_src[href]
        return m.group(0)
    for name in mdn_js:
        doc = mdn_js[name]
        if "summary" in doc:
            doc["summary"] = re.sub("href=\"(.*?)\"", replace_href, doc["summary"])
        if "member" in doc:
            for member in doc:
                member["help"] = re.sub("href=\"(.*?)\"", replace_href, member["help"])

with open("mdn-css.json") as f:
    mdn_css = json.load(f)

def generate_interface(interface):
    if interface.id in haxerenderer.merged_targets:
        return # Skip merged classes

    if interface.id in haxerenderer.haxe_idl_types:
        return # Skip built-in types

    path = haxerenderer.to_haxe(interface.id)
    name = path[-1]
    package = path[0:-1]

    file_path = os.sep.join([root_dir, generated_dir] + package + [name+".hx"])
    _logger.debug("Generating %s" % file_path)

    dir_name = os.path.dirname(file_path)
    if not os.path.exists(dir_name):
        _logger.debug("Creating directory %s" % dir_name)
        os.makedirs(dir_name)

    # Render the IDLInterface object into text.
    text = haxerenderer.render(db, interface, mdn_js, mdn_css, header=header)

    with open(file_path, "w") as f:
        f.write(text.encode("utf8"))

for interface in db.GetInterfaces():
    generate_interface(interface)
