from django.apps import apps
from django.contrib import admin
from django.shortcuts import HttpResponse
from django.contrib.admin.sites import AlreadyRegistered
from django_summernote.admin import SummernoteModelAdmin
from .models import Announcement, Edition, School, Student
from django.db import transaction

from io import BytesIO
import xlsxwriter


class AnnouncementModelAdmin(SummernoteModelAdmin):
    summernote_fields = ['content']


class EditionModelAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'active')
    ordering = ('-active', '-year')

    change_form_template = 'admin/edition_buttons.html'

    def response_change(self, request, obj):
        if '_update-student-scores' in request.POST:
            file = obj.scores.open(mode='r')
            content = filter(lambda x: x != '', file.read().split('\n'))
            file.close()

            rows = [x.split(',') for x in content]

            with transaction.atomic():
                for index, row in enumerate(rows):
                    if index == 0:
                        continue

                    Student.objects.filter(identifier=row[0]).update(score_first=row[1], score_second=row[2])

        if '_update-disable-submissions' in request.POST and obj.active and obj.submissions:
            if obj.active is True:
                schools = School.objects.all()

                with transaction.atomic():
                    for school in schools:
                        school.updateTeam()

                    obj.submissions = False
                    obj.save()

        if '_generate-student-list' in request.POST:
            year = obj.year
            students = Student.objects.filter(identifier__startswith=year)
            schools_set = {int(student.identifier.split('-')[1]) for student in students}

            output = BytesIO()
            workbook = xlsxwriter.Workbook(output)

            worksheet = workbook.add_worksheet("Lista uczniów")

            worksheet.write(0, 0, 'Identyfikator')
            worksheet.write(0, 1, 'Wynik - eliminacje')
            worksheet.write(0, 2, 'Wynik - finał')
            worksheet.write(0, 3, 'Imię')
            worksheet.write(0, 4, 'Nazwisko')
            worksheet.write(0, 5, 'Klasa')
            worksheet.write(0, 6, 'Szkoła - nazwa')
            worksheet.write(0, 7, 'Szkoła - miejscowość')
            worksheet.write(0, 8, 'Szkoła - adres')

            row = 1
            for school_id in schools_set:
                for student in sorted(Student.objects.filter(identifier__startswith=f'{year}-{school_id}-'), key=lambda x: x.identifier.split('-')[2]):
                    worksheet.write(row, 0, student.identifier)  # Identyfikator
                    worksheet.write(row, 1, student.score_first)  # Wynik - eliminacje
                    worksheet.write(row, 2, student.score_second)  # Wynik - finał
                    worksheet.write(row, 3, student.name)  # Imię
                    worksheet.write(row, 4, student.surname)  # Nazwisko
                    worksheet.write(row, 5, student.grade)  # Klasa
                    worksheet.write(row, 6, student.school_name)  # Szkoła - nazwa
                    worksheet.write(row, 7, student.school_town)  # Szkoła - miejscowość
                    worksheet.write(row, 8, student.school_address)  # Szkoła - adres

                    row += 1

            workbook.close()
            xlsx_data = output.getvalue()

            response = HttpResponse(content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=Uczniowie.xlsx'
            response.write(xlsx_data)

            return response

        return super().response_change(request, obj)


class StudentModelAdmin(admin.ModelAdmin):
    list_display = ('identifier', '__str__', 'grade')
    search_fields = ('identifier', 'name', 'surname', 'grade')
    ordering = ('identifier',)


admin.site.register(Student, StudentModelAdmin)
admin.site.register(Announcement, AnnouncementModelAdmin)
admin.site.register(Edition, EditionModelAdmin)


app_models = apps.get_app_config('app').get_models()
for model in app_models:
    try:
        admin.site.register(model)
    except AlreadyRegistered:
        pass

admin.site.site_header = 'Puchar Dyrektora LO V'
admin.site.site_title = 'Puchar LO V'
admin.site.index_title = 'Panel administracyjny'
admin.site.site_url = '/'
admin.site.enable_nav_sidebar = False
