import csv

from django.core.management.base import BaseCommand, CommandError
import django.contrib.auth.models as auth_models
from django.db import transaction

from ... import models

class Command(BaseCommand):
    args = '<directory>'
    help = 'Dump user list as CSV'

    def dict_to_utf8(self, d):
        for key in d:
            d[key] = d[key].encode('utf8')

    def save_users(self, path):
        with open(path, 'w') as f:
            headers = ['username', 
                       'password',
                       'prenom', 
                       'nom', 
                       'email', 
                       'profil',
                       'groupe']
            csv_handle = csv.DictWriter(f, headers)
            users = auth_models.User.objects.filter(is_superuser=False, delegations_by__isnull=True)
            csv_handle.writerow(dict(zip(csv_handle.fieldnames, csv_handle.fieldnames)))
            if not users.count():
                raise CommandError('No users, nothing to archive !! Already archived maybe...')
            for user in users:
                d = {
                    'username': user.username,
                    'prenom': user.first_name,
                    'nom': user.last_name,
                    'email': user.email,
                    'password': user.password,
                    'profil': ','.join([ml.name for ml in user.mailing_lists.all()]),
                    'groupe': ','.join([group.name for group in user.groups.all()])}
                self.dict_to_utf8(d)
                csv_handle.writerow(d)

    @transaction.commit_on_success
    def handle(self, *args, **options):
        path = args[0]
        self.save_users(path)
