from django.contrib import admin
from django.core import serializers
from django.http import HttpResponse

from troggle.core.models.caves import Cave, CaveAndEntrance, Entrance
from troggle.core.models.logbooks import QM, LogbookEntry, PersonLogEntry
from troggle.core.models.survex import (
    DrawingFile,
    SingleScan,
    SurvexBlock,
    SurvexFile,
    SurvexPersonRole,
    SurvexStation,
)
from troggle.core.models.wallets import Wallet
from troggle.core.models.troggle import DataIssue, Expedition, Person, PersonExpedition

"""This code significantly adds to the capabilities of the Django Management control panel for Troggle data.
In particular, it enables JSON export of any data with 'export_as_json'
and configures the search fields to be used within the control panel.

What is the search path for the css and js inclusions  in the Media subclasses though ?!

The page looks for /static/jquery/jquery.min.js
"""


class TroggleModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        """overriding admin save to fill the new_since parsing_field

        new_since_parsing is not currently used in troggle. It is a fossil."""
        obj.new_since_parsing = True
        obj.save()

    class Media:
        js = ("jquery/jquery.min.js", "js/QM_helper.js")  # not currently available to troggle, see media/js/README


class RoleInline(admin.TabularInline):
    model = SurvexPersonRole
    extra = 4


class SurvexBlockAdmin(TroggleModelAdmin):
    inlines = (RoleInline,)


# class QMsFoundInline(admin.TabularInline):
    # model = QM
    # fk_name = "found_by"
    # fields = ("number", "grade", "location_description", "comment")  # need to add foreignkey to cave part
    # extra = 1


class PersonLogEntryInline(admin.TabularInline):
    model = PersonLogEntry
    raw_id_fields = ("personexpedition",)
    extra = 1


class LogbookEntryAdmin(TroggleModelAdmin):
    prepopulated_fields = {"slug": ("title",)}
    search_fields = ("title", "expedition__year")
    date_heirarchy = "date"
    # inlines = (PersonLogEntryInline, QMsFoundInline)

    class Media:
        css = {"all": ("css/troggleadmin.css",)}  # this does not exist

    actions = ("export_logbook_entries_as_html", "export_logbook_entries_as_txt")

    def export_logbook_entries_as_html(self, modeladmin, request, queryset):
        response = downloadLogbook(request=request, queryset=queryset, extension="html")  # fails, no queryset
        return response

    def export_logbook_entries_as_txt(self, modeladmin, request, queryset):
        response = downloadLogbook(request=request, queryset=queryset, extension="txt")  # fails, no queryset
        return response


class PersonExpeditionInline(admin.TabularInline):
    model = PersonExpedition
    extra = 1


class PersonAdmin(TroggleModelAdmin):
    search_fields = ("first_name", "last_name")
    inlines = (PersonExpeditionInline,)


class QMAdmin(TroggleModelAdmin):
    search_fields = ("number", "expoyear")
    list_display = ("__str__", "grade")
    list_display_links = ("__str__",)
    # list_editable = ("comment", "page_ref", "grade")
    # list_per_page = 20
    # raw_id_fields = ("found_by", "ticked_off_by")


class PersonExpeditionAdmin(TroggleModelAdmin):
    search_fields = ("person__first_name", "expedition__year")


class CaveAdmin(TroggleModelAdmin):
    search_fields = ("official_name", "kataster_number", "unofficial_number")
    extra = 4


class EntranceAdmin(TroggleModelAdmin):
    search_fields = ("caveandentrance__cave__kataster_number",)


class SurvexStationAdmin(TroggleModelAdmin):
    search_fields = ("name",)


class SurvexFileAdmin(TroggleModelAdmin):
    search_fields = ("path",)


# class SurvexDirectoryAdmin(TroggleModelAdmin):
    # search_fields = (
        # "path",
        # "survexdirectory",
    # )


class DrawingFileAdmin(TroggleModelAdmin):
    search_fields = ("dwgname",)


class WalletAdmin(TroggleModelAdmin):
    search_fields = ("fpath",)


admin.site.register(Cave, CaveAdmin)
#admin.site.register(Area)
admin.site.register(CaveAndEntrance)
admin.site.register(Entrance, EntranceAdmin)
admin.site.register(SurvexBlock, SurvexBlockAdmin)
admin.site.register(DrawingFile, DrawingFileAdmin)
admin.site.register(Expedition)
admin.site.register(Person, PersonAdmin)
admin.site.register(SurvexPersonRole)
#admin.site.register(SurvexDirectory, SurvexDirectoryAdmin)
admin.site.register(SurvexFile, SurvexFileAdmin)
admin.site.register(SurvexStation, SurvexStationAdmin)
admin.site.register(PersonExpedition, PersonExpeditionAdmin)
admin.site.register(LogbookEntry, LogbookEntryAdmin)
admin.site.register(QM, QMAdmin)
admin.site.register(Wallet, WalletAdmin)
admin.site.register(SingleScan)
admin.site.register(DataIssue)


def export_as_json(modeladmin, request, queryset):
    response = HttpResponse(content_type="text/json")
    response["Content-Disposition"] = "attachment; filename=troggle_output.json"
    serializers.serialize("json", queryset, stream=response)
    return response


def export_as_xml(modeladmin, request, queryset):
    response = HttpResponse(content_type="text/xml")
    response["Content-Disposition"] = "attachment; filename=troggle_output.xml"
    serializers.serialize("xml", queryset, stream=response)
    return response


admin.site.add_action(export_as_xml)
admin.site.add_action(export_as_json)