# -*- coding: utf-8 -*-

import os
from mob import *

class GenError(Exception):
    pass

class Generator:

    def __init__(self, l, type = "enemies", floor = "Other"):
        self.type = type
        self.floor = floor
        self.floor_ = floor.replace(' ', '_').lower()
        self.mobs = []
        self.add(l)

    def add(self, l):
        if isinstance(l, list):
            for i,mob in enumerate(l):
                if isinstance(mob, Entity):
                    self.mobs.append(mob)
                else:
                    raise GenError('mob {0} must be a list of Entity'.format(i))
        else:
            if isinstance(mob, Enemy):
                self.mobs.append(l)
            else:
                raise GenError('mob {0} must be a list of Entity'.format(i))

    def make(self):
        p = '../{}_py/functions'.format(self.type)
        if not os.path.exists(p):
            os.makedirs(p)
            print("Directory ", p , " Created ")

        for mob in self.mobs:
            f = open('../{0}_py/functions/{1}.mcfunction'.format(self.type, mob.name_), 'w')
            f.write("""# Max % 2/3
scoreboard players set min rng 0
scoreboard players set max rng 1500
function rng:interval""")
            f.write('\n\nexecute if score global curse <= out rng run summon {0} ~ ~ ~ {1}'.format(mob.mob, mob.nbt()))
            f.write('\n\nexecute if score global curse > out rng run summon {0} ~ ~ ~ {1}'.format(mob.mob, mob.nbt(True)))
            for command in mob.commands:
                f.write('\n\n'+command)
            if "custom_sound" in mob.tags:
                f.write("\n\nexecute as @e[tag={},tag=init,sort=nearest,limit=1] run function 0_enemy_boss:sound_cooldown/spawn".format(mob.name_))
            f.write("\n\ntag @e[tag={},tag=init,sort=nearest,limit=1] remove init".format(mob.name_))
            f.close()

        self.book_root()
        self.book_floor_root()
        self.book_type_root()
        self.book_register_mob()

# -------- Book ------
    def book_register_mob(self):
        for i,mob in enumerate(self.mobs):
            parent_path = 'book_py:{}/{}/{}_{}'.format(self.floor_, self.type, i-1, self.mobs[i-1].name_)
            if i == 0:
                parent_path = 'book_py:{}/{}/root'.format(self.floor_, self.type)
            fpath = 'book_py:{}/{}'.format(self.type, mob.name_)

            description = '''
        [
            {{"text":"Stats:","color":"gray"}},{{"text":"\\n"}},
            {{"text":"  \\u2022 {} ","color":"dark_gray"}},{{"text":"\\uf810","color":"white","italic":false}},{{"text":"\\n"}},
            {{"text":"  \\u2022 {} ","color":"dark_gray"}},{{"text":"\\uf811","color":"white","italic":false}},{{"text":"\\n"}},
            {{"text":"  \\u2022 {} ","color":"dark_gray"}},{{"text":"\\uf813","color":"white","italic":false}},{{"text":"\\n"}},
            {{"text":"  \\u2022 {} ","color":"dark_gray"}},{{"text":"\\uf816","color":"white","italic":false}}
        ]'''.format(mob.hp, mob.attack_damage, mob.movement_speed, mob.knockback_resistance if mob.knockback_resistance != None else "0")

            data = '''
{{
    "display": {{
        "title": {0}                ,
        "description": {1},
        "icon": {{
            "item": "minecraft:{2}",
            "nbt":"{{{3}}}"
        }},
        "frame": "task",
        "show_toast": true,
        "announce_to_chat": false,
        "hidden": true
    }},
    "criteria": {{
        "{4}": {{
            "trigger": "minecraft:player_killed_entity",
            "conditions": {{
                "entity":{{
                    "nbt": "{{Tags:[\\"{4}\\"]}}"
                }}
            }}
        }}
    }},
    "rewards": {{
       "function": "{5}"
    }},
    "parent": "{6}"
}}
'''.format(JLine([mob.name]).get_book(name = True), description, mob.icon["item"], mob.icon["nbt"], mob.name_, fpath, parent_path)

            f = open('../book_py/advancements/{}/{}/{}_{}.json'.format(self.floor_, self.type, i, mob.name_),'w')
            f.write(data)
            f.close()

            f = open('../book_py/functions/{}/{}.mcfunction'.format(self.type, mob.name_),'w')
            f.write("advancement grant @a only book_py:{}/{}/root {}".format(self.floor_, self.type, mob.name_))
            f.close()

    def book_type_root(self):
        criteria = ''
        for i,mob in enumerate(self.mobs):
            criteria += '\n\t\t\t"{0}":{{"trigger": "minecraft:impossible"}}'.format(mob.name_)
            if i+1 < len(self.mobs):
                criteria += ','

        color = "dark_red" if self.type != "enemies" else "red"
        icon = "skeleton_skull" if self.type == "enemies" else "wither_skeleton_skull"
        data = '''
{{
    "display": {{
        "title": {{
            "text": "{}",
            "color": "{}"
        }},
        "description": {{
            "text": ""
        }},
        "icon": {{
            "item": "minecraft:{}"
        }},
        "frame": "goal",
        "show_toast": true,
        "announce_to_chat": false,
        "hidden": false
    }},
    "criteria": {{ {}
    }},
    "parent": "book_py:{}/root"
}}
'''.format(self.type.capitalize(), color, icon, criteria, self.floor_)
        f = open("../book_py/advancements/{0}/{1}/root.json".format(self.floor_, self.type),'w')
        f.write(data)
        f.close()

    def book_floor_root(self):
        model = {"tutorial":5014,"others":5015,"floor_1":5016,"floor_2":5017}
        data = '''
{{
    "display": {{
        "title": {{
            "text": "{0}",
            "color": "gold"
        }},
        "description": {{
            "text": ""
        }},
        "icon": {{
            "item": "minecraft:slime_ball",
            "nbt":"{{CustomModelData:{1}}}"
        }},
        "frame": "goal",
        "show_toast": false,
        "announce_to_chat": false,
        "hidden": false
    }},
    "criteria": {{
        "null": {{"trigger": "minecraft:tick"}}
    }},
    "parent": "book_py:root"
}}
'''.format(self.floor, model[self.floor_])
        f = open('../book_py/advancements/{}/root.json'.format(self.floor_),'w')
        f.write(data)
        f.close()

    def book_root(self):
        p = '../book_py/advancements/{}/{}'.format(self.floor_, self.type)
        if not os.path.exists(p):
            os.makedirs(p)
            print("Directory ", p , " Created ")
        p = '../book_py/functions/{}'.format(self.type)
        if not os.path.exists(p):
            os.makedirs(p)
            print("Directory ", p , " Created ")

        data = '''
{
    "display": {
        "title": {
            "text": "Mobs",
            "color": "gold"
        },
        "description": {
            "text": ""
        },
        "icon": {
            "item": "minecraft:zombie_head"
        },
        "frame": "challenge",
        "show_toast": false,
        "announce_to_chat": false,
        "hidden": false,
        "background": "minecraft:textures/block/nether_wart_block.png"
    },
    "criteria": {
        "null": {"trigger": "minecraft:tick"}
    }
}
'''
        f = open('../book_py/advancements/root.json','w')
        f.write(data)
        f.close()
