import uuid
from django.contrib.auth import get_user_model
from authentic2.a2_rbac.models import Role, OrganizationalUnit
from django.utils.encoding import force_text
import csv

User = get_user_model()

ou = OrganizationalUnit.objects.get(default=True)
reader = csv.reader(open('comptes.csv'))
lines = list(reader)
roles_check = {}
roles = {}

for line in lines[2:]:
    line = map(force_text, line)
    try:
        commune, email, first_name, last_name, role_name, role_slug = line
    except:
        print line
    # verify coherence of roles
    assert roles_check.setdefault(role_name, role_slug) == role_slug
    assert roles_check.setdefault(role_slug, role_name) == role_name
    if role_slug not in roles:
        roles[role_slug] = Role.objects.get_or_create(slug=role_slug,
                                                      defaults={'name': role_name, 'ou' : ou})[0]
        assert roles[role_slug].name == role_name
    role = roles[role_slug]
    user = User.objects.get_or_create(email=email)[0]
    user.set_password(str(uuid.uuid4()))
    user.ou = ou
    user.first_name = first_name
    user.last_name = last_name
    user.save()
    user.roles = [role]
