from django.contrib import admin
from django import forms
from django.forms.models import BaseInlineFormSet
from django.contrib.gis.db import models as geo_models
from leaflet.admin import LeafletGeoAdmin, LeafletGeoAdminMixin, LeafletWidget
from nested_inline.admin import NestedStackedInline, NestedModelAdmin
from . import models
from . import analysiscsv

@admin.register(models.EventType)
class EventType(admin.ModelAdmin):
    pass

@admin.register(models.Location)
class Location(LeafletGeoAdmin):
    def _get_map_widget(self, db_field, widget):
        widget = super()._get_map_widget(db_field, widget)
        widget.display_raw = True
        return widget

@admin.register(models.DistributionType)
class DistributionType(admin.ModelAdmin):
    fields = (('name', 'abbreviation'), 'has_shape_parameter')

@admin.register(models.StatisticalMethod)
class StatisticalMethod(admin.ModelAdmin):
    pass

@admin.register(models.AttributionVariable)
class AttributionVariable(admin.ModelAdmin):
    fields = (('short_name', 'long_name'), ('unit', 'unit_symbol', 'delta_I_unit_symbol'), 'description')

@admin.register(models.ObservationDataSet)
class ObservationDataSet(admin.ModelAdmin):
    fields = ('name', 'description', ('url', 'doi'), 'papers')

@admin.register(models.ModelDataSet)
class ModelDataSet(admin.ModelAdmin):
    fields = ('model_name', 'model_description', 'experiment', 'experiment_description',('url', 'doi'), 'papers')

@admin.register(models.JournalPaper)
class JournalPaper(admin.ModelAdmin):
    fields = ('title', 'authors', ('journal', 'issue', 'date'), ('url', 'doi'))

@admin.register(models.PressCommunication)
class PressRelease(admin.ModelAdmin):
    fields = ('title', 'authors', ('medium', 'date'), ('url', 'doi'))
    pass


def small_inputs():
    return { geo_models.CharField: {'widget': forms.TextInput(attrs={'size':'32'})},
        geo_models.TextField: {'widget': forms.Textarea(attrs={'rows':'3', 'cols':'40'})},
        geo_models.FloatField: {'widget': forms.TextInput(attrs={'size':'6'})},
        geo_models.IntegerField: {'widget': forms.NumberInput(attrs={'style':'width:6ch'})},
        geo_models.PositiveIntegerField: {'widget': forms.NumberInput(attrs={'style':'width:6ch'})},}


class SetRequestFormset(BaseInlineFormSet):
    """
    A custom formset that sets its 'request' member var
    as a member var for every form produced from it. This is
    useful for communicating the request object from e.g.
    TabularInline to a ModelForm instance, allowing messages
    to be generated therein.
    """
    def _construct_form(self, i, **kwargs):
        form = super(SetRequestFormset, self)._construct_form(i, **kwargs)
        form.request = self.request
        return form


class ModelAnalysisInline(admin.TabularInline):
    model = models.ModelAnalysis
    form = analysiscsv.ModelAnalysisAdminForm
    formfield_overrides = small_inputs()
    formset = SetRequestFormset
    extra = 0
    inlines = []

    def get_formset(self, request, obj=None, **kwargs):
        """
        Extends the ususal get_formset() behaviour to include the request
        object as a member var for the returned formset. In conjunction
        with SetRequestFormset, this can be used to pass the request object
        through to the ModelForm instances, so that they may generate django
        user messages.
        """
        formset = super(ModelAnalysisInline, self).get_formset(request, obj, **kwargs)
        formset.request = request
        return formset


class ObservationAnalysisInline(admin.TabularInline):
    model = models.ObservationAnalysis
    form = analysiscsv.ObservationAnalysisAdminForm
    formfield_overrides = small_inputs()
    formset = SetRequestFormset
    extra = 0
    inlines = []

    def get_formset(self, request, obj=None, **kwargs):
        """
        Extends the ususal get_formset() behaviour to include the request
        object as a member var for the returned formset. In conjunction
        with SetRequestFormset, this can be used to pass the request object
        through to the ModelForm instances, so that they may generate django
        user messages.
        """
        formset = super(ObservationAnalysisInline, self).get_formset(request, obj, **kwargs)
        formset.request = request
        return formset



class AttributionInline(NestedStackedInline):
    model = models.Attribution
    extra = 0
    fieldsets = ( (None, {'fields': (('description', 'location'),)}),
                  ('Method', {'fields': (('variable', 'distribution', 'statistical_method'),)}),
                  ('Synthesis', {'fields' : ('return_period', ('PR', 'PR_min', 'PR_max'), ('Delta_I', 'Delta_I_min', 'Delta_I_max'), 'conclusions')}),
                  ('Dissemination', {'fields' : ('contact', 'webpage', 'papers', 'press_communication', ('research_data', 'research_data_doi'))}), )
    inlines = [ObservationAnalysisInline, ModelAnalysisInline]


class ImpactResourceInline(NestedStackedInline):
    model = models.ImpactResource
    extra = 0


@admin.register(models.Event)
class Event(LeafletGeoAdminMixin, NestedModelAdmin):
    fieldsets = ( (None, {'fields': ('name', 'event_type', 'image', 'image_caption', 'comments')}),
                ('Event Definition', {'fields' : (('region','map_location'), ('start_date', 'duration', 'season'))}),
                ('Impact', {'fields' : (('deaths', 'people_affected', 'economical_loss'), ('socio_economic_impact'), ('environmental_impact'))}),
                ('Attribution request', {'fields': ('attribution_consideration_statement',)}) )
    inlines = [
        ImpactResourceInline, AttributionInline,
    ]


    def _get_map_widget(self, db_field, widget):
        widget = super()._get_map_widget(db_field, widget)
        widget.map_height = "200px"
        widget.map_width = "100%"
        return widget

from django.contrib import admin
from django import forms
from django.forms.models import BaseInlineFormSet
from django.contrib.gis.db import models as geo_models
from leaflet.admin import LeafletGeoAdmin, LeafletGeoAdminMixin, LeafletWidget
from nested_inline.admin import NestedStackedInline, NestedModelAdmin
from . import models
from . import analysiscsv

@admin.register(models.EventType)
class EventType(admin.ModelAdmin):
    pass

@admin.register(models.Location)
class Location(LeafletGeoAdmin):
    def _get_map_widget(self, db_field, widget):
        widget = super()._get_map_widget(db_field, widget)
        widget.display_raw = True
        return widget

@admin.register(models.DistributionType)
class DistributionType(admin.ModelAdmin):
    fields = (('name', 'abbreviation'), 'has_shape_parameter')

@admin.register(models.StatisticalMethod)
class StatisticalMethod(admin.ModelAdmin):
    pass

@admin.register(models.AttributionVariable)
class AttributionVariable(admin.ModelAdmin):
    fields = (('short_name', 'long_name'), ('unit', 'unit_symbol', 'delta_I_unit_symbol'), 'description')

@admin.register(models.ObservationDataSet)
class ObservationDataSet(admin.ModelAdmin):
    fields = ('name', 'description', ('url', 'doi'), 'papers')

@admin.register(models.ModelDataSet)
class ModelDataSet(admin.ModelAdmin):
    fields = ('model_name', 'model_description', 'experiment', 'experiment_description',('url', 'doi'), 'papers')

@admin.register(models.JournalPaper)
class JournalPaper(admin.ModelAdmin):
    fields = ('title', 'authors', ('journal', 'issue', 'date'), ('url', 'doi'))

@admin.register(models.PressCommunication)
class PressRelease(admin.ModelAdmin):
    fields = ('title', 'authors', ('medium', 'date'), ('url', 'doi'))
    pass


def small_inputs():
    return { geo_models.CharField: {'widget': forms.TextInput(attrs={'size':'32'})},
        geo_models.TextField: {'widget': forms.Textarea(attrs={'rows':'3', 'cols':'40'})},
        geo_models.FloatField: {'widget': forms.TextInput(attrs={'size':'6'})},
        geo_models.IntegerField: {'widget': forms.NumberInput(attrs={'style':'width:6ch'})},
        geo_models.PositiveIntegerField: {'widget': forms.NumberInput(attrs={'style':'width:6ch'})},}


class SetRequestFormset(BaseInlineFormSet):
    """
    A custom formset that sets its 'request' member var
    as a member var for every form produced from it. This is
    useful for communicating the request object from e.g.
    TabularInline to a ModelForm instance, allowing messages
    to be generated therein.
    """
    def _construct_form(self, i, **kwargs):
        form = super(SetRequestFormset, self)._construct_form(i, **kwargs)
        form.request = self.request
        return form


class ModelAnalysisInline(admin.TabularInline):
    model = models.ModelAnalysis
    form = analysiscsv.ModelAnalysisAdminForm
    formfield_overrides = small_inputs()
    formset = SetRequestFormset
    extra = 0
    inlines = []

    def get_formset(self, request, obj=None, **kwargs):
        """
        Extends the ususal get_formset() behaviour to include the request
        object as a member var for the returned formset. In conjunction
        with SetRequestFormset, this can be used to pass the request object
        through to the ModelForm instances, so that they may generate django
        user messages.
        """
        formset = super(ModelAnalysisInline, self).get_formset(request, obj, **kwargs)
        formset.request = request
        return formset


class ObservationAnalysisInline(admin.TabularInline):
    model = models.ObservationAnalysis
    form = analysiscsv.ObservationAnalysisAdminForm
    formfield_overrides = small_inputs()
    formset = SetRequestFormset
    extra = 0
    inlines = []

    def get_formset(self, request, obj=None, **kwargs):
        """
        Extends the ususal get_formset() behaviour to include the request
        object as a member var for the returned formset. In conjunction
        with SetRequestFormset, this can be used to pass the request object
        through to the ModelForm instances, so that they may generate django
        user messages.
        """
        formset = super(ObservationAnalysisInline, self).get_formset(request, obj, **kwargs)
        formset.request = request
        return formset



class AttributionInline(NestedStackedInline):
    model = models.Attribution
    extra = 0
    fieldsets = ( (None, {'fields': (('description', 'location'),)}),
                  ('Method', {'fields': (('variable', 'distribution', 'statistical_method'),)}),
                  ('Synthesis', {'fields' : ('return_period', ('PR', 'PR_min', 'PR_max'), ('Delta_I', 'Delta_I_min', 'Delta_I_max'), 'conclusions')}),
                  ('Dissemination', {'fields' : ('contact', 'webpage', 'papers', 'press_communication', ('research_data', 'research_data_doi'))}), )
    inlines = [ObservationAnalysisInline, ModelAnalysisInline]


class ImpactResourceInline(NestedStackedInline):
    model = models.ImpactResource
    extra = 0


@admin.register(models.Event)
class Event(LeafletGeoAdminMixin, NestedModelAdmin):
    fieldsets = ( (None, {'fields': ('name', 'event_type', 'image', 'image_caption', 'comments')}),
                ('Event Definition', {'fields' : (('region','map_location'), ('start_date', 'duration', 'season'))}),
                ('Impact', {'fields' : (('deaths', 'people_affected', 'economical_loss'), ('socio_economic_impact'), ('environmental_impact'))}),
                ('Attribution request', {'fields': ('attribution_consideration_statement',)}) )
    inlines = [
        ImpactResourceInline, AttributionInline,
    ]


    def _get_map_widget(self, db_field, widget):
        widget = super()._get_map_widget(db_field, widget)
        widget.map_height = "200px"
        widget.map_width = "100%"
        return widget

A custom formset that sets its 'request' member var     as a member var for every form produced from it. This is     useful for communicating the request object from e.g.     TabularInline to a ModelForm instance, allowing messages     to be generated therein. Extends the ususal get_formset() behaviour to include the request         object as a member var for the returned formset. In conjunction         with SetRequestFormset, this can be used to pass the request object         through to the ModelForm instances, so that they may generate django         user messages. Extends the ususal get_formset() behaviour to include the request         object as a member var for the returned formset. In conjunction         with SetRequestFormset, this can be used to pass the request object         through to the ModelForm instances, so that they may generate django         user messages.