import csv

from django.contrib import admin

# Register your models here.
from django.http import HttpResponse
from django.urls import reverse
from django.utils.html import format_html

from assignments.helpers import write_assignments_to_csv, write_submissions_to_csv
from assignments.models import Assignment, StudentSubmission, SubmissionFeedback


class StudentSubmissionInline(admin.TabularInline):
    model = StudentSubmission

    readonly_fields = ('link', 'document', 'student', 'final',)
    exclude = ('text',)
    extra = 0

    def link(self, obj):
        return format_html('<a href={}>{}</a>'.format(reverse('admin:assignments_studentsubmission_change', args=(obj.id,)), obj.text))


@admin.register(Assignment)
class AssignmentAdmin(admin.ModelAdmin):
    list_display = ('title', 'module', 'deleted', 'owner', )
    autocomplete_fields = ('owner',)
    actions = ['export_assignments_to_csv', 'export_submissions_to_csv']
    list_filter = ('owner', 'module', 'user_created')
    search_fields = ('id', 'title')

    inlines = [
        StudentSubmissionInline
    ]

    def export_assignments_to_csv(self, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;filename=assignment-export.csv'

        writer = csv.writer(response)
        write_assignments_to_csv(writer, queryset)

        return response

    export_assignments_to_csv.short_description = 'Auftragstexte exportieren'

    def export_submissions_to_csv(self, request, queryset):
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;filename=assignment-submission-export.csv'

        writer = csv.writer(response)
        write_submissions_to_csv(writer, queryset)

        return response

    export_submissions_to_csv.short_description = 'Lösungstexte exportieren'


@admin.register(StudentSubmission)
class StudentSubmissionAdmin(admin.ModelAdmin):
    pass

@admin.register(SubmissionFeedback)
class SubmissionFeedbackAdmin(admin.ModelAdmin):
    pass

