import json


from roglick.engine.ecs import System, exceptions
from roglick.components import SkillComponent,SkillSubComponent
from roglick.engine import event,random
from roglick.events import SkillCheckEvent


SKILL_TREE = {}


class SkillTreeNode(object):
    def __init__(self, attr, parent):
        self._attr = attr
        self._parent = parent

    @property
    def attr(self):
        return self._attr

    @property
    def parent_name(self):
        return self._parent

    @property
    def parent(self):
        if self._parent is None:
            return None
        else:
            return SKILL_TREE[self._parent]

    def __repr__(self):
        parent = self.parent
        if parent is None:
            return "{cls}({attr})".format(
                    cls=self.__class__.__name__,
                    attr=self.attr)
        else:
            return "{cls}({attr}, {parentname}:{parentnode})".format(
                    cls=self.__class__.__name__,
                    attr=self.attr,
                    parentname=self.parent_name,
                    parentnode=parent)


def _build_skill_tree():
    with open('data/skills.json') as fh:
        data = json.load(fh)

    for skill in data:
        SKILL_TREE[skill] = SkillTreeNode(**data[skill])
_build_skill_tree()


class SkillSystem(System):
    @event.event_handler(SkillCheckEvent)
    def skill_check_handler(self, checkevent):
        checkevent.result = self.check_skill(
                checkevent.entity, checkevent.skill, checkevent.modifier)

    def check_skill(self, entity, skill, modifier=0):
        skill_level = self.get_skill_level(entity, skill) + modifier

        roll = 100
        for n in range(3):
            roll = min(roll, random.roll_dice(3))
            print("Rolling....", roll)

        success = roll <= skill_level or roll <= 4
        critical = roll <= 6 and roll*3 <= skill_level
        dos = skill_level - roll

        if critical:
            dos += random.roll_dice()

        return (roll, dos, success, critical)

    def get_skill_level(self, entity, skill):
        if skill is None:
            return 0

        parent_level = self.get_skill_level(entity, SKILL_TREE[skill].parent_name)

        return self.get_skill(entity, skill).ranks + parent_level/2

    def get_skill(self, entity, skill):
        try:
            e = self._entity_manager.get_component(
                    entity, SkillComponent)
        except exceptions.NoComponentForEntityError:
            e = SkillComponent()
            self._entity_manager.set_component(entity, e)

        try:
            comp = e.skills[skill]
        except KeyError:
            comp = SkillSubComponent()
            e.skills[skill] = comp

        return comp


@@ -1756,47 +1756,8 @@
 (3))
-%0A            print(%22Rolling....%22, roll)
 %0A%0A  

Remove debugging code