# Path: sshkm/models.py
# class Key(models.Model):
#     name = models.CharField(max_length=191, unique=True)
#     description = models.CharField(max_length=191, null=True, blank=True)
#     firstname = models.CharField(max_length=191, null=True, blank=True)
#     lastname = models.CharField(max_length=191, null=True, blank=True)
#     email = models.EmailField(max_length=191, null=True, blank=True)
#     publickey = models.TextField(null=True, blank=True)
#     member_of = models.ManyToManyField('Group', through='KeyGroup', blank=True)
# 
# class KeyGroup(models.Model):
#     key = models.ForeignKey('Key', on_delete=models.CASCADE)
#     group = models.ForeignKey('Group', on_delete=models.CASCADE)
# 
# class Group(models.Model):
#     name = models.CharField(max_length=191, unique=True)
#     description = models.CharField(max_length=191, null=True, blank=True)
#     members = models.ManyToManyField('Key', through='KeyGroup', blank=True)
# 
# Path: sshkm/forms.py
# class KeyForm(forms.ModelForm):
#     class Meta:
#         model = Key
#         fields = ('name', 'email', 'description', 'firstname', 'lastname', 'publickey', 'member_of',)
#         labels = {
#             'name': _('Name (unique)'),
#             'email': _('Email (optional)'),
#             'description': _('Description (optional)'),
#             'firstname': _('Firstname (optional)'),
#             'lastname': _('Lastname (optional)'),
#             'publickey': _('Public Key'),
#         }
# 
#     def __init__(self, *args, **kwargs):
#         super(KeyForm, self).__init__(*args, **kwargs)
#         self.fields['member_of'] = ModelMultipleChoiceFieldNames(queryset=Group.objects.all(), required=False, label='Member of Group(s)')
#         self.fields['name'].widget.attrs['placeholder'] = ''
#         self.fields['email'].widget.attrs['placeholder'] = ''
#         self.fields['firstname'].widget.attrs['placeholder'] = ''
#         self.fields['lastname'].widget.attrs['placeholder'] = ''
#         self.fields['description'].widget.attrs['placeholder'] = ''
#         self.fields['publickey'].widget.attrs['placeholder'] = 'ssh-rsa AAAAB3NzaC1yc......== user@example.com'


from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.core.exceptions import ObjectDoesNotExist
from sshkm.models import Key, KeyGroup, Group
from sshkm.forms import KeyForm
@login_required
def KeyDelete(request):
    try:
        keys = Key.objects.filter(id__in=request.GET.getlist('id', request.POST.getlist('id'))) # calls getlist on POST only if getlist of GET is None
        size = len(keys)

        if size > 0:
            messages.add_message(request, messages.SUCCESS, "Keys deleted") if size > 1 else messages.add_message(request, messages.SUCCESS, "Key " + keys.first().name+ " deleted")
            keys.delete()
        else:
            messages.add_message(request, messages.ERROR, "The key could not be deleted. Key does not exist")
    except Exception as e:
        messages.add_message(request, messages.ERROR, "The key could not be deleted: "+str(e))

    return HttpResponseRedirect(reverse('KeyList'))

@login_required
def KeySave(request):
    try:
        key = Key(
            id=request.POST.get('id'),
            name=request.POST.get('name'),
            description=request.POST.get('description'),
            firstname=request.POST.get('firstname', False),
            lastname=request.POST.get('lastname', False),
            email=request.POST.get('email'),
            publickey=request.POST.get('publickey', '').replace("\n", "").replace("\r", ""),
        )
        
        if key.id is not None:

# Path: sshkm/models.py
# class Key(models.Model):
#     name = models.CharField(max_length=191, unique=True)
#     description = models.CharField(max_length=191, null=True, blank=True)
#     firstname = models.CharField(max_length=191, null=True, blank=True)
#     lastname = models.CharField(max_length=191, null=True, blank=True)
#     email = models.EmailField(max_length=191, null=True, blank=True)
#     publickey = models.TextField(null=True, blank=True)
#     member_of = models.ManyToManyField('Group', through='KeyGroup', blank=True)
# 
# class KeyGroup(models.Model):
#     key = models.ForeignKey('Key', on_delete=models.CASCADE)
#     group = models.ForeignKey('Group', on_delete=models.CASCADE)
# 
# class Group(models.Model):
#     name = models.CharField(max_length=191, unique=True)
#     description = models.CharField(max_length=191, null=True, blank=True)
#     members = models.ManyToManyField('Key', through='KeyGroup', blank=True)
# 
# Path: sshkm/forms.py
# class KeyForm(forms.ModelForm):
#     class Meta:
#         model = Key
#         fields = ('name', 'email', 'description', 'firstname', 'lastname', 'publickey', 'member_of',)
#         labels = {
#             'name': _('Name (unique)'),
#             'email': _('Email (optional)'),
#             'description': _('Description (optional)'),
#             'firstname': _('Firstname (optional)'),
#             'lastname': _('Lastname (optional)'),
#             'publickey': _('Public Key'),
#         }
# 
#     def __init__(self, *args, **kwargs):
#         super(KeyForm, self).__init__(*args, **kwargs)
#         self.fields['member_of'] = ModelMultipleChoiceFieldNames(queryset=Group.objects.all(), required=False, label='Member of Group(s)')
#         self.fields['name'].widget.attrs['placeholder'] = ''
#         self.fields['email'].widget.attrs['placeholder'] = ''
#         self.fields['firstname'].widget.attrs['placeholder'] = ''
#         self.fields['lastname'].widget.attrs['placeholder'] = ''
#         self.fields['description'].widget.attrs['placeholder'] = ''
#         self.fields['publickey'].widget.attrs['placeholder'] = 'ssh-rsa AAAAB3NzaC1yc......== user@example.com'


# Path: sshkm/views/key.py
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db import IntegrityError
from django.core.exceptions import ObjectDoesNotExist
from sshkm.models import Key, KeyGroup, Group
from sshkm.forms import KeyForm

@login_required
def KeyDelete(request):
    try:
        keys = Key.objects.filter(id__in=request.GET.getlist('id', request.POST.getlist('id'))) # calls getlist on POST only if getlist of GET is None
        size = len(keys)

        if size > 0:
            messages.add_message(request, messages.SUCCESS, "Keys deleted") if size > 1 else messages.add_message(request, messages.SUCCESS, "Key " + keys.first().name+ " deleted")
            keys.delete()
        else:
            messages.add_message(request, messages.ERROR, "The key could not be deleted. Key does not exist")
    except Exception as e:
        messages.add_message(request, messages.ERROR, "The key could not be deleted: "+str(e))

    return HttpResponseRedirect(reverse('KeyList'))

@login_required
def KeySave(request):
    try:
        key = Key(
            id=request.POST.get('id'),
            name=request.POST.get('name'),
            description=request.POST.get('description'),
            firstname=request.POST.get('firstname', False),
            lastname=request.POST.get('lastname', False),
            email=request.POST.get('email'),
            publickey=request.POST.get('publickey', '').replace("\n", "").replace("\r", ""),
        )
        
        if key.id is not None:

            KeyGroup.objects.filter(key_id=key.id).delete()