import xml.etree.ElementTree as ET
import os

def html_table_row(line, colspan=1):
    return f"<tr><td colspan='{colspan}'>{line}</td></tr>"

def html_table_row2(left, right):
    return f"<tr><td>{left}</td><td align='right'>{right}</td></tr>"

def to_str_percent(strFloat):
    return str(int(float(strFloat) * 100.0)) + "%"

def create_modifier(e_modifier):
    t = e_modifier.tag

    if t == "abilities":
        html = "Abilities<ul>"
        for ab in e_modifier:
            str_name = ab.attrib["name"]
            str_value = ab.attrib["value"]
            html += f"<li>{str_name} {str_value}</li>"
        html += "</ul>"
        return html
    elif t == "attributes":
        html = "Attributes<ul>"
        for at in e_modifier:
            str_name = at.attrib["name"]
            str_value = at.attrib["value"]
            html += f"<li>{str_name} {str_value}</li>"
        html += "</ul>"
        return html
    elif t == "critChance":
        return f"Crit Chance {e_modifier.text}"
    elif t == "hitChanceAttacker":
        return f"Hit Chance Attacker {e_modifier.text}"
    elif t == "hitChanceDefender":
        return f"Hit Chance Defener {e_modifier.text}"
    elif t == "damageReductions":
        html = "Damage Reduction<ul>"
        for dr in e_modifier:
            str_component = dr.attrib["component"]
            str_type = dr.attrib["type"]
            str_value = dr.attrib["value"]
            html += f"<li>{str_type} {str_value} {str_component}</li>"
        html += "</ul>"
        return html
    elif t == "damageResistances":
        html = "Damage Resistances<ul>"
        for dr in e_modifier:
            str_component = dr.attrib["component"]
            str_type = dr.attrib["type"]
            str_value = dr.attrib["value"]
            html += f"<li>{str_type} {str_value} {str_component}</li>"
        html += "</ul>"
        return html
    elif t == "immunities":
        html = "Immunities<ul>"
        for im in e_modifier:
            str_ref = im.attrib["ref"]
            html += f"<li><a href=\"../condition/{str_ref}.html\">{str_ref}</a></li>"
        html += "</ul>"
        return html
    else:
        return e_modifier.tag

def create_combat_action_action(e_action: ET.Element):
    t = e_action.tag
    if t == "addCondition":
        str_ref = e_action.attrib["ref"]

        e_duration = e_action.find("duration")
        if e_duration != None:
            str_duration = ""
            if "days" in e_duration.attrib:
                str_duration += e_duration.attrib["days"] + "d"
            if "hours" in e_duration.attrib:
                str_duration += e_duration.attrib["hours"] + "h"
            if "minutes" in e_duration.attrib:
                str_duration += e_duration.attrib["minutes"] + "m"
            if "seconds" in e_duration.attrib:
                str_duration += e_duration.attrib["seconds"] + "s"
            
        e_chance = e_action.find("chance")
        if e_chance != None:
            str_chance = to_str_percent(e_chance.text)
        else:
            str_chance = None

        html = f"<b>Add Condition</b> <a href='../condition/{str_ref}.html'>{str_ref}</a>"
        if str_duration != None:
            html += f" {str_duration}"
        if str_chance != None:
            html += f" ({str_chance})"

        return html
    elif t == "dealDamage":
        str_component = e_action.attrib["component"]
        str_type = e_action.attrib["type"]
        str_min = e_action.attrib["min"]
        str_max = e_action.attrib["max"]
        return f"<b>Deal Damage</b> {str_type} {str_min}-{str_max} {str_component}"
    elif t == "learnCombatAction":
        str_ref = e_action.attrib["ref"]
        return f"<b>Learn</b> <a href='../combat_action/{str_ref}.html'>{str_ref}</a>"
    elif t == "removeCondition":
        str_ref = e_action.attrib["ref"]
        return f"<b>Remove Condition</b> <a href='../condition/{str_ref}.html'>{str_ref}</a>"
    elif t == "restoreAP":
        str_min = e_action.attrib["min"]
        str_max = e_action.attrib["max"]
        return f"<b>Restore AP</b> {str_min}-{str_max}"
    elif t == "restoreDamage":
        str_component = e_action.attrib["component"]
        str_min = e_action.attrib["min"]
        str_max = e_action.attrib["max"]
        return f"<b>Restore Damage</b> {str_min}-{str_max} {str_component}"
    elif t == "restoreHP":
        str_min = e_action.attrib["min"]
        str_max = e_action.attrib["max"]
        return f"<b>Restore HP</b> {str_min}-{str_max}"
    else:
        return e_action.tag + " " + str(e_action.attrib)


def create_combat_action_html(filepath):
    tree = ET.parse(filepath)
    root = tree.getroot()

    html = ""
    html += "<table border width='400'>"


    str_name = root.find("name").text
    html += html_table_row(f"<h2>{str_name}</h2>")

    str_ap_cost = root.find("cost").text
    str_target = root.find("target").text
    str_range_from = root.find("range").attrib["from"]
    str_range_to = root.find("range").attrib["to"]
    html += html_table_row(f"<b>AP</b> {str_ap_cost}")
    html += html_table_row(f"<b>Target</b> {str_target}")
    html += html_table_row(f"<b>Range</b> {str_range_from} {str_range_to}")

    str_hit_chance = to_str_percent(root.find("hitChance").text)
    str_crit_chance = to_str_percent(root.find("critChance").text)
    str_crit_multi = root.find("critMultiplier").text
    html += html_table_row(f"<b>Hit</b> {str_hit_chance} <b>Crit</b> {str_crit_chance} (x{str_crit_multi})")

    str_description = root.find("description").text
    html += html_table_row(str_description)

    e_requirements = root.find("requirements")
    if e_requirements != None:
        data = "<b>Requirements</b><ul>"
        for e_requirement in e_requirements:
            print(e_requirement.tag, e_requirement.attrib)
            if e_requirement.tag == "ability":
                str_name = e_requirement.attrib["name"]
                str_value = e_requirement.attrib["value"]
                data += f"<li>Ability: {str_name} {str_value}</li>"
            elif e_requirement.tag == "trait":
                str_name = e_requirement.attrib["name"]
                data += f"<li>Trait: {str_name}</li>"
            else:
                pass
        data += "</ul>"
        html += html_table_row(data)

    e_actions = root.find("actions")
    data = "<b>Actions</b><ul>"
    for e_action in e_actions:
        data += "<li>" + create_combat_action_action(e_action) + "</li>"
    data += "</ul>"
    html += html_table_row(data)

    html += "</table>"
    return html


def create_condition_html(filepath):
    tree = ET.parse(filepath)
    root = tree.getroot()

    html = ""
    html += "<table border width='400'>"

    str_name = root.find("name").text
    html += html_table_row(f"<h2>{str_name}</h2>")

    e_description = root.find("description")
    if e_description != None:
        html += html_table_row(e_description.text)
    else:
        html += html_table_row("None")

    e_cannot_run = root.find("cannotRun")
    if e_cannot_run != None:
        html += html_table_row(f"<b>Cannot run</b> {e_cannot_run.text}")

    e_remove_on_attack = root.find("removeOnAttack")
    if e_remove_on_attack != None:
        html += html_table_row(f"<b>Remove on attack</b> {e_remove_on_attack.text}")

    e_remove_on_damage = root.find("removeOnDamage")
    if e_remove_on_damage != None:
        html += html_table_row(f"<b>Remove on damage</b> {e_remove_on_damage.text}")

    e_skip_turn = root.find("skipTurn")
    if e_skip_turn != None:
        html += html_table_row(f"<b>Skip turn</b> {e_skip_turn.text}")

    e_actions = root.find("actions")
    if e_actions != None:
        data = "Actions<ul>"
        for e_action in e_actions:
            data += "<li>"
            data += create_combat_action_action(e_action)
            data += "</li>"
        data += "</ul>"
        html += html_table_row(data)

    e_modifiers = root.find("modifiers")
    if e_modifiers != None:
        data = "Modifiers<ul>"
        for e_modifier in e_modifiers:
            data += "<li>"
            data += create_modifier(e_modifier)
            data += "</li>"
        data += "</ul>"
        html += html_table_row(data)

    html += "</table>"
    return html


def create_creature_html(filepath):
    tree = ET.parse(filepath)
    root = tree.getroot()

    html = ""
    html += "<table border width='400'>"
    html +=  "<tr><td colspan='2'>"
    str_name = root.find("name").text
    html += f"<h2>{str_name}</h2>"
    html += "</td></tr>"

    str_hp = root.find("hp").text
    str_mp = root.find("ap").text
    str_vim = root.find("vim").text
    html += html_table_row(f"<b>HP</b> {str_hp} <b>AP</b> {str_mp} <b>VIM</b> {str_vim}")

    e_abilities = root.find("abilities")
    if e_abilities != None:
        html += "<tr><td>"
        html += "<table>"
        for e_ability in e_abilities:
            str_name = e_ability.attrib["name"]
            str_value = e_ability.attrib["value"]
            html += f"<tr><td>{str_name}</td><td align='right'>{str_value}</td></tr>"
        html += "</table>"
        html += "</td></tr>"

    e_combat_actions = root.find("combatActions")
    if e_combat_actions != None:
        data = "Combat Actions<ul>"
        for e_combat_action in e_combat_actions:
            str_ref = e_combat_action.attrib["ref"]
            data += f"<li><a href='../combat_action/{str_ref}.html'>{str_ref}</a></li>"
        data += "</ul>"
        html += html_table_row(data)

    e_modifiers = root.find("modifiers")
    if e_modifiers != None:
        data = "Modifiers<ul>"
        for e_modifier in e_modifiers:
            data += "<li>"
            data += create_modifier(e_modifier)
            data += "</li>"
        data += "</ul>"
        html += html_table_row(data)

    e_item_drops = root.find("itemDrops")
    if e_item_drops != None:
        html += html_table_row("Item Drops") # TODO

    html += "</table>"
    return html

def create_item_html(filepath):
    tree = ET.parse(filepath)
    root = tree.getroot()

    html = ""
    html += "<table border width='400'>"

    str_name = root.find("name").text
    html += html_table_row(f"<h2>{str_name}</h2>")

    str_type = root.attrib["type"]
    html += html_table_row(f"<b>Type</b> {str_type}")

    str_description = root.find("description").text
    html += html_table_row(str_description) 

    e_actions = root.find("actions")
    if e_actions != None:
        data = "Actions<ul>"
        for e_action in e_actions:
            data += "<li>"
            data += create_combat_action_action(e_action)
            data += "</li>"
        data += "</ul>"
        html += html_table_row(data)


    e_modifiers = root.find("modifiers")
    if e_modifiers != None:
        data = "Modifiers<ul>"
        for e_modifier in e_modifiers:
            data += "<li>"
            data += create_modifier(e_modifier)
            data += "</li>"
        data += "</ul>"
        html += html_table_row(data)

    e_requirements = root.find("requirements")
    if e_requirements != None:
        data = "Requirements<ul>"
        for e_requirement in e_requirements:
            data += "<li>"
            data += e_requirement.tag + " " + str(e_requirement.attrib)
            data += "</li>"
        data += "</ul>"
        html += html_table_row(data)

    html += "</table>"
    return html

###############################################################################
# directories
###############################################################################

def create_directory(dir, create_html_from_xml_file):
    xml_file_list = []
    for _, _, files in os.walk(f"db/{dir}"):
        for file in files:
            xml_file_list.append(file)

    html = ""

    for file in xml_file_list:
        print(file)
        html_combat_action = create_html_from_xml_file(f"db/{dir}/{file}")

        file_html = file.replace(".xml", ".html")

        os.makedirs(os.path.dirname(f"doc/{dir}/{file_html}"), exist_ok=True)
        with open(f"doc/{dir}/{file_html}", "w") as f:
            f.write(html_combat_action)

        html += "<p>"
        html += html_combat_action
        html += "</p>"

    os.makedirs(os.path.dirname(f"doc/{dir}/index.html"), exist_ok=True)
    with open(f"doc/{dir}/index.html", "w") as f:
        f.write(html)


def create_combat_action_dir(dir):
    create_directory(dir, create_combat_action_html)
def create_condition_dir(dir):
    create_directory(dir, create_condition_html)
def create_creature_dir(dir):
    create_directory(dir, create_creature_html)
def create_item_dir(dir):
    create_directory(dir, create_item_html)


create_combat_action_dir("combat_action")
create_condition_dir("condition")
create_creature_dir("creature")
create_item_dir("item")