from redminelib import Redmine
from requests.adapters import HTTPAdapter

from redminelib.resources.base import BaseResource

# make baseresource hashable


def BR__hash__(self):
    return hash(int(self))


def BR__eq__(self, other):
    return self.__class__ is other.__class__ and self.id == other.id

BaseResource.__hash__ = BR__hash__
BaseResource.__eq__ = BR__eq__

redmine = Redmine('https://dev.entrouvert.org/', username='bdauvergne', password='eiBubee5')
redmine.engine.session.mount('http://', HTTPAdapter(max_retries=3))
redmine.engine.session.mount('https://', HTTPAdapter(max_retries=3))

projects = list(redmine.project.all())
projects_id_map = {p.id: p for p in projects}
roles = list(redmine.role.all())
roles_id_map = {r.id: r for r in roles}
groups = list(redmine.group.all())
groups_id_map = {g.id: g for g in groups}
trackers = list(redmine.tracker.all())

projects_children = {p: [] for p in projects}
for p in projects:
    if hasattr(p, 'parent'):
        projects_children[projects_id_map[p.parent.id]].append(p)

for p in projects_children:
    projects_children[p].sort(key=lambda p: p.name)


def get_project(name):
    for p in projects:
        if p.name == name:
            return p
    raise KeyError


def get_role(name):
    for r in roles:
        if r.name == name:
            return r
    raise KeyError


def get_group(name):
    for g in groups:
        if g.name == name:
            return g
    raise KeyError

def get_tracker(name):
    for t in trackers:
        if t.name == name:
            return t
    raise KeyError

projects.sort(key=lambda p: (len(projects_children[p]), p.name))


def map_projects(f, roots=[]):
    roots = roots or [p for p in projects if not hasattr(p, 'parent')]

    def helper(p, level=0):
        if f(p, level):
            for child in projects_children[p]:
                helper(child, level=level + 1)

    for root in roots:
        helper(root)
