# Path: authentication/models.py
# class User(AbstractBaseUser, PermissionsMixin):
#     main_character_id = models.PositiveIntegerField(primary_key=True)
#     email = models.EmailField(max_length=255, null=True, blank=True)
#     is_staff = models.BooleanField(default=False)
#     is_active = models.BooleanField(default=False)
# 
#     USERNAME_FIELD = 'main_character_id'
#     REQUIRED_FIELDS = []
# 
#     objects = UserManager()
# 
#     class Meta:
#         verbose_name = 'user'
#         verbose_name_plural = 'users'
# 
#     @property
#     def main_character(self):
#         if self.characters.filter(id=self.main_character_id).exists():
#             return self.characters.get(id=self.main_character_id)
#         elif EVECharacter.objects.filter(id=self.main_character_id).exists():
#             logger.warn("User with main character ID %s has detached main character model" % self.get_full_name())
#             return EVECharacter.objects.get(id=self.main_character_id)
#         else:
#             return None
# 
#     def get_full_name(self):
#         return str(self.main_character_id)
#     def get_short_name(self):
#         if self.main_character:
#             return str(self.main_character)
#         else:
#             return self.get_full_name()
# 
#     def __unicode__(self):
#         if self.main_character:
#             return str(self.main_character).encode('utf-8')
#         else:
#             logger.debug("Missing character model for user with main character id %s, returning id as __unicode__." % self.main_character_id)
#             return self.get_short_name().encode('utf-8')
# 
# Path: access/models.py
# class CharacterAccessRule(BaseAccessRule):
# 
#     character = models.OneToOneField(EVECharacter, models.CASCADE)
#     access = GenericRelation('access.UserAccess')
#     auto_group = GenericRelation('groupmanagement.AutoGroup')
# 
#     def __unicode__(self):
#         output = 'character %s' % self.character
#         return output.encode('utf-8')
# 
#     def generate_useraccess(self):
#         ct = ContentType.objects.get_for_model(self)
#         logger.debug("Assigning UserAccess by CharacterAccess rule %s" % self)
#         characters = EVECharacter.objects.filter(id=self.character.id)
#         useraccess = self.access.all()
#         self._validate_rule(characters, useraccess)
# 
# class CorpAccessRule(BaseAccessRule):
# 
#     corp = models.OneToOneField(EVECorporation, models.CASCADE)
#     access = GenericRelation('access.UserAccess')
#     auto_group = GenericRelation('groupmanagement.AutoGroup')
# 
#     def __unicode__(self):
#         output = 'corp %s' % self.corp
#         return output.encode('utf-8')
# 
#     def generate_useraccess(self):
#         ct = ContentType.objects.get_for_model(self)
#         logger.debug("Assigning UserAccess by CorpAccess rule %s" % self)
#         characters = EVECharacter.objects.filter(corp_id=self.corp.id)
#         useraccess = self.access.all()
#         self._validate_rule(characters, useraccess)
# 
# class AllianceAccessRule(BaseAccessRule):
# 
#     alliance = models.OneToOneField(EVEAlliance, models.CASCADE)
#     access = GenericRelation('access.UserAccess')
#     auto_group = GenericRelation('groupmanagement.AutoGroup')
# 
#     def __unicode__(self):
#         output = 'alliance %s' % self.alliance
#         return output.encode('utf-8')
# 
#     def generate_useraccess(self):
#         ct = ContentType.objects.get_for_model(self)
#         logger.debug("Assigning UserAccess by AllianceAccess rule %s" % self)
#         characters = EVECharacter.objects.filter(alliance_id=self.alliance.id)
#         useraccess = self.access.all()
#         self._validate_rule(characters, useraccess)


from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import Group
from authentication.models import User
from forms import GroupAddForm, GroupEditForm, GroupTransferForm, AutoGroupForm
from models import GroupApplication, ExtendedGroup, AutoGroup
from access.models import CharacterAccessRule, CorpAccessRule, AllianceAccessRule
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
import logging
@login_required
@permission_required('access.site_access')
@permission_required('groupmanagement.add_autogroup')
def auto_group_add(request):
    logger.debug("auto_group_add called by user %s" % request.user)
    choices = []
    for aa in AllianceAccessRule.objects.all():
        if not aa.auto_group.exists():
            choices.append(('alliance %s' % aa.pk, aa))
    for ca in CorpAccessRule.objects.all():
        if not ca.auto_group.exists():
            choices.append(('corp %s' % ca.pk, ca))
    for ca in CharacterAccessRule.objects.all():
        if not ca.auto_group.exists():
            choices.append(('character %s' % ca.pk, ca))
    logger.debug(choices)
    if request.method == 'POST':
        form = AutoGroupForm(request.POST)
        form.fields['access_rule'].choices = choices
        if form.is_valid():
            name = form.cleaned_data['name']
            group, c = Group.objects.get_or_create(name=name)
            if not c:
                form.add_error(None, 'Somehow that group already exists. Pick a different name')
            else:
                access_str = str.split(str(form.cleaned_data['access_rule']))
                type = access_str[0]
                id = access_str[1]
                rule = None
                if type == "alliance":

# Path: authentication/models.py
# class User(AbstractBaseUser, PermissionsMixin):
#     main_character_id = models.PositiveIntegerField(primary_key=True)
#     email = models.EmailField(max_length=255, null=True, blank=True)
#     is_staff = models.BooleanField(default=False)
#     is_active = models.BooleanField(default=False)
# 
#     USERNAME_FIELD = 'main_character_id'
#     REQUIRED_FIELDS = []
# 
#     objects = UserManager()
# 
#     class Meta:
#         verbose_name = 'user'
#         verbose_name_plural = 'users'
# 
#     @property
#     def main_character(self):
#         if self.characters.filter(id=self.main_character_id).exists():
#             return self.characters.get(id=self.main_character_id)
#         elif EVECharacter.objects.filter(id=self.main_character_id).exists():
#             logger.warn("User with main character ID %s has detached main character model" % self.get_full_name())
#             return EVECharacter.objects.get(id=self.main_character_id)
#         else:
#             return None
# 
#     def get_full_name(self):
#         return str(self.main_character_id)
#     def get_short_name(self):
#         if self.main_character:
#             return str(self.main_character)
#         else:
#             return self.get_full_name()
# 
#     def __unicode__(self):
#         if self.main_character:
#             return str(self.main_character).encode('utf-8')
#         else:
#             logger.debug("Missing character model for user with main character id %s, returning id as __unicode__." % self.main_character_id)
#             return self.get_short_name().encode('utf-8')
# 
# Path: access/models.py
# class CharacterAccessRule(BaseAccessRule):
# 
#     character = models.OneToOneField(EVECharacter, models.CASCADE)
#     access = GenericRelation('access.UserAccess')
#     auto_group = GenericRelation('groupmanagement.AutoGroup')
# 
#     def __unicode__(self):
#         output = 'character %s' % self.character
#         return output.encode('utf-8')
# 
#     def generate_useraccess(self):
#         ct = ContentType.objects.get_for_model(self)
#         logger.debug("Assigning UserAccess by CharacterAccess rule %s" % self)
#         characters = EVECharacter.objects.filter(id=self.character.id)
#         useraccess = self.access.all()
#         self._validate_rule(characters, useraccess)
# 
# class CorpAccessRule(BaseAccessRule):
# 
#     corp = models.OneToOneField(EVECorporation, models.CASCADE)
#     access = GenericRelation('access.UserAccess')
#     auto_group = GenericRelation('groupmanagement.AutoGroup')
# 
#     def __unicode__(self):
#         output = 'corp %s' % self.corp
#         return output.encode('utf-8')
# 
#     def generate_useraccess(self):
#         ct = ContentType.objects.get_for_model(self)
#         logger.debug("Assigning UserAccess by CorpAccess rule %s" % self)
#         characters = EVECharacter.objects.filter(corp_id=self.corp.id)
#         useraccess = self.access.all()
#         self._validate_rule(characters, useraccess)
# 
# class AllianceAccessRule(BaseAccessRule):
# 
#     alliance = models.OneToOneField(EVEAlliance, models.CASCADE)
#     access = GenericRelation('access.UserAccess')
#     auto_group = GenericRelation('groupmanagement.AutoGroup')
# 
#     def __unicode__(self):
#         output = 'alliance %s' % self.alliance
#         return output.encode('utf-8')
# 
#     def generate_useraccess(self):
#         ct = ContentType.objects.get_for_model(self)
#         logger.debug("Assigning UserAccess by AllianceAccess rule %s" % self)
#         characters = EVECharacter.objects.filter(alliance_id=self.alliance.id)
#         useraccess = self.access.all()
#         self._validate_rule(characters, useraccess)


# Path: groupmanagement/views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import Group
from authentication.models import User
from forms import GroupAddForm, GroupEditForm, GroupTransferForm, AutoGroupForm
from models import GroupApplication, ExtendedGroup, AutoGroup
from access.models import CharacterAccessRule, CorpAccessRule, AllianceAccessRule
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.decorators import login_required, permission_required, user_passes_test
import logging

@login_required
@permission_required('access.site_access')
@permission_required('groupmanagement.add_autogroup')
def auto_group_add(request):
    logger.debug("auto_group_add called by user %s" % request.user)
    choices = []
    for aa in AllianceAccessRule.objects.all():
        if not aa.auto_group.exists():
            choices.append(('alliance %s' % aa.pk, aa))
    for ca in CorpAccessRule.objects.all():
        if not ca.auto_group.exists():
            choices.append(('corp %s' % ca.pk, ca))
    for ca in CharacterAccessRule.objects.all():
        if not ca.auto_group.exists():
            choices.append(('character %s' % ca.pk, ca))
    logger.debug(choices)
    if request.method == 'POST':
        form = AutoGroupForm(request.POST)
        form.fields['access_rule'].choices = choices
        if form.is_valid():
            name = form.cleaned_data['name']
            group, c = Group.objects.get_or_create(name=name)
            if not c:
                form.add_error(None, 'Somehow that group already exists. Pick a different name')
            else:
                access_str = str.split(str(form.cleaned_data['access_rule']))
                type = access_str[0]
                id = access_str[1]
                rule = None
                if type == "alliance":

                    rule = get_object_or_404(AllianceAccessRule, pk=id)