# Path: buttons.py
# class ButtonableModelAdmin(admin.ModelAdmin):
#     """
#         A subclass of this admin will let you add buttons (like history) in the
#         change view of an entry.
#     """
#     buttons = []
# 
#     def change_view(self, request, object_id, form_url='', extra_context=None):
#         if not extra_context:
#             extra_context = {'buttons' : []}
# 
#         for b in self.buttons:
#             extra_context['buttons'].append({'name' : b.short_description, 'url' : b.func_name})
# 
#         return super(ButtonableModelAdmin, self).change_view(request, object_id, form_url, extra_context)
# 
#     def get_urls(self):
#         urls = super(ButtonableModelAdmin, self).get_urls()
# 
#         my_urls = patterns('',)
#         for b in self.buttons:
#             my_urls += patterns('',
#                             url(r'^(?P<id>\d+)/%s/$' % b.func_name, self.admin_site.admin_view(b))
#                         )
# 
#         return my_urls + urls
# 
#     def __call__(self, request, url):
#         if url is not None:
#             res=re.match('(.*/)?(?P<id>\d+)/(?P<command>.*)/', url)
#             if res:
#                 if res.group('command') in [b.func_name for b in self.buttons]:
#                     obj = self.model._default_manager.get(pk=res.group('id'))
#                     getattr(self, res.group('command'))(obj)
#                     return HttpResponseRedirect(request.META['HTTP_REFERER'])
# 
#         return super(ButtonableModelAdmin, self).__call__(request, url)
# 
# Path: github.py
# def _get_user_repo(url):
#     """
#         Return the :user/:repo/ from a github.com url
#     """
#     if url.find('://github.com/') > -1:  # toplevel GitHub page
#         p = url.split('/')
#         return '%s/%s' % (p[3], p[4].replace('.git', ''))
#     elif url.find('.github.com/') > -1:  # GitHub project pages
#         p = url.split('/')
#         u = p[2].split('.')[0]
#         return '%s/%s' % (u, p[3])
# 
#     return None


import re
import sys
import bugs
import utils
import difio.tasks
from models import *
from django.contrib import admin
from django.contrib import messages
from django.shortcuts import render
from buttons import ButtonableModelAdmin
from datetime import datetime, timedelta
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.core.files.base import ContentFile
from django.contrib.admin import SimpleListFilter
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.models import AnonymousUser
from github import _get_user_repo as github_get_user_repo
    from django.contrib.messages import constants as message_levels




class ApplicationAdmin(admin.ModelAdmin):
    list_display = ('name', 'owner', 'uuid', 'vendor', 'status', 'last_checkin')
    list_filter = ('status', 'date_approved')
    search_fields = ['name', 'uuid']

class InstalledPackageListFilter(SimpleListFilter):
    """
        Filter Packages which are installed.
    """
    title = "Installed"
    parameter_name = 'is_installed'

    def lookups(self, request, model_admin):
        return (
            ('1', 'Yes'),
            ('0', 'No'),
        )

    def queryset(self, request, queryset):
        if self.value() == '1':
            q = InstalledPackage.objects.only('package').distinct()
            return queryset.filter(pk__in=set(inst.package for inst in q))
        else:
            # NB: if value is 0 it will always return ALL objects, not NON installed
            return queryset


# Path: buttons.py
# class ButtonableModelAdmin(admin.ModelAdmin):
#     """
#         A subclass of this admin will let you add buttons (like history) in the
#         change view of an entry.
#     """
#     buttons = []
# 
#     def change_view(self, request, object_id, form_url='', extra_context=None):
#         if not extra_context:
#             extra_context = {'buttons' : []}
# 
#         for b in self.buttons:
#             extra_context['buttons'].append({'name' : b.short_description, 'url' : b.func_name})
# 
#         return super(ButtonableModelAdmin, self).change_view(request, object_id, form_url, extra_context)
# 
#     def get_urls(self):
#         urls = super(ButtonableModelAdmin, self).get_urls()
# 
#         my_urls = patterns('',)
#         for b in self.buttons:
#             my_urls += patterns('',
#                             url(r'^(?P<id>\d+)/%s/$' % b.func_name, self.admin_site.admin_view(b))
#                         )
# 
#         return my_urls + urls
# 
#     def __call__(self, request, url):
#         if url is not None:
#             res=re.match('(.*/)?(?P<id>\d+)/(?P<command>.*)/', url)
#             if res:
#                 if res.group('command') in [b.func_name for b in self.buttons]:
#                     obj = self.model._default_manager.get(pk=res.group('id'))
#                     getattr(self, res.group('command'))(obj)
#                     return HttpResponseRedirect(request.META['HTTP_REFERER'])
# 
#         return super(ButtonableModelAdmin, self).__call__(request, url)
# 
# Path: github.py
# def _get_user_repo(url):
#     """
#         Return the :user/:repo/ from a github.com url
#     """
#     if url.find('://github.com/') > -1:  # toplevel GitHub page
#         p = url.split('/')
#         return '%s/%s' % (p[3], p[4].replace('.git', ''))
#     elif url.find('.github.com/') > -1:  # GitHub project pages
#         p = url.split('/')
#         u = p[2].split('.')[0]
#         return '%s/%s' % (u, p[3])
# 
#     return None


# Path: admin.py
import re
import sys
import bugs
import utils
import difio.tasks
from models import *
from django.contrib import admin
from django.contrib import messages
from django.shortcuts import render
from buttons import ButtonableModelAdmin
from datetime import datetime, timedelta
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.core.files.base import ContentFile
from django.contrib.admin import SimpleListFilter
from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth.models import AnonymousUser
from github import _get_user_repo as github_get_user_repo
    from django.contrib.messages import constants as message_levels





class ApplicationAdmin(admin.ModelAdmin):
    list_display = ('name', 'owner', 'uuid', 'vendor', 'status', 'last_checkin')
    list_filter = ('status', 'date_approved')
    search_fields = ['name', 'uuid']

class InstalledPackageListFilter(SimpleListFilter):
    """
        Filter Packages which are installed.
    """
    title = "Installed"
    parameter_name = 'is_installed'

    def lookups(self, request, model_admin):
        return (
            ('1', 'Yes'),
            ('0', 'No'),
        )

    def queryset(self, request, queryset):
        if self.value() == '1':
            q = InstalledPackage.objects.only('package').distinct()
            return queryset.filter(pk__in=set(inst.package for inst in q))
        else:
            # NB: if value is 0 it will always return ALL objects, not NON installed
            return queryset


class PackageAdmin(ButtonableModelAdmin):