from sys import stdout

from django.contrib import admin
from django.http import HttpResponse
from django.core import serializers
from cve_parser.forms import CVEEntryForm

from cve_parser.models import CVEEntry, SoftwareList, Reference, CVSSBaseMetric


class CveEntriesAdmin(admin.ModelAdmin):
    list_display = (
        'cve_id', 'summary', 'published_time', 'last_modified_time', 'get_cvsss_score', 'get_affected__product')
    actions = ['export_as_json']
    list_filter = ('cvss_base_metrics__score', 'software_list__product')
    form = CVEEntryForm
    list_per_page = 20
    ordering = ('cve_id',)
    search_fields = ('cve_id',)

    def export_as_json(modeladmin, request, queryset):
        response = HttpResponse(content_type="application/json")
        kwargs = {}
        for filter, arg in request.GET.items():
            kwargs.update({filter: arg})
        queryset = modeladmin.model.objects.all().filter(**kwargs)
        stdout.write(serializers.serialize("json", queryset, stream=response, indent=2))
        response['Content-Disposition'] = 'attachment; filename=myfile.json'
        return response

    export_as_json.short_description = "Export all %(verbose_name_plural)s in Json"
    export_as_json.acts_on_all = True

    def changelist_view(self, request, extra_context=None):
        try:
            action = self.get_actions(request)[request.POST['action']][0]
            action_acts_on_all = action.acts_on_all
        except (KeyError, AttributeError):
            action_acts_on_all = False

        if action_acts_on_all:
            post = request.POST.copy()
            post.update({admin.helpers.ACTION_CHECKBOX_NAME: None})
            request._set_post(post)
        return super(CveEntriesAdmin, self).changelist_view(request, extra_context)


class CvssBaseMetricsAdmin(admin.ModelAdmin):
    ordering = ('score',)
    list_display = (
        'score', 'access_vector', 'access_complexity', 'authentication', 'confidentiality_impact', 'integrity_impact',
        'availability_impact', 'source', 'generated_datetime'
    )


class SoftwareListAdmin(admin.ModelAdmin):
    ordering = ('product',)
    list_display = ('product',)


class ReferencesAdmin(admin.ModelAdmin):
    ordering = ('source_name',)
    list_display = ('source_name', 'source_type', 'source_url', 'source_text')


admin.site.register(CVEEntry, CveEntriesAdmin)
admin.site.register(CVSSBaseMetric, CvssBaseMetricsAdmin)
admin.site.register(SoftwareList, SoftwareListAdmin)
admin.site.register(Reference, ReferencesAdmin)
