# -*- coding: utf-8 -*-
from config import *
import sys

projets_clients = get_project('Projets Clients')
entrouvert = get_group('Entr\'ouvert')
gestion_de_projet = get_role('Gestion de projet')
developpeur = get_role(u'Développeur')
developpement = get_tracker(u'Développement')


def print_tree(roots=[]):
    def helper(p, level):
        prefix = ''
        if level > 0:
            prefix += '+--'
        if level > 1:
            prefix += '-' * (level - 1) * 2
        if developpement in list(p.trackers):
            print(prefix, p.name, p.id, list(tracker.name for tracker in p.trackers))
        memberships = redmine.project_membership.filter(project_id=p.id)
        for m in memberships:
            if hasattr(m, 'user'):
                name = m.user.name
            else:
                name = m.group['name']
            if all(r.name != 'CPF' for r in m.roles):
                continue
            print(' ' * len(prefix), '%30s' % name, ', '.join([r.name for r in m.roles]))
        if level == 0:
            return True
    map_projects(helper, roots=roots)

print_tree(roots=[projets_clients])


def remove_developpeur_from_entrouvert_roles(p, level):
    memberships = redmine.project_membership.filter(project_id=p.id)

    for m in memberships:
        if not hasattr(m, 'group'):
            continue
        if m.group['id'] == entrouvert.id:
            break
    else:
        return True

    # m is Entr'ouvert membership
    for role in m.roles:
        if role.id == developpeur.id:
            break
    else:
        return True

    roles = list(role for role in m.roles if not getattr(role, 'inherited', False) and role.id != developpeur.id)
    roles.append(gestion_de_projet)
    m.roles = roles
    m.save()

    return True

# map_projects(remove_developpeur_from_entrouvert_roles, roots=[projets_clients])
