from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType

from debtors.models.debtors import Debtor
from debtors.models.invoices import Invoice

User = get_user_model()
PERMISSIONS = ['view', 'add', 'change', 'delete']
IBAN = 'AO06004500530000728780515'


def create_group_and_permissions():
    """Create admin staff group and add permissions"""
    ct_debtor = ContentType.objects.get_for_model(Debtor)
    ct_invoice = ContentType.objects.get_for_model(Invoice)
    group, _ = Group.objects.get_or_create(name='adminstaff')
    for permission in PERMISSIONS:
        name_debtor = '{}_{}'.format(permission,
                                     Debtor.__name__.lower())
        name_invoice = '{}_{}'.format(permission,
                                      Invoice.__name__.lower())
        permission_debtor = Permission.objects.get(
            codename=name_debtor,
            content_type=ct_debtor,
        )
        permission_invoice, _ = Permission.objects.get_or_create(
            codename=name_invoice,
            content_type=ct_invoice,
        )
        group.permissions.add(permission_debtor, permission_invoice)

    return group


def create_user(username=None, email=None, password=None, is_staff=False):
    """Create an user"""
    data = {
        'username': username or 'user',
        'email': email or 'email',
        'password': password or 'sup3rCompl3xP@ssword',
        'is_staff': is_staff or True,
    }
    user = User.objects.create_user(**data)
    if is_staff:
        group = create_group_and_permissions()
        user.groups.add(group)
    return user
