"""
Brochures admin..
"""
import os
import datetime
from django.conf import settings
from django.contrib import admin
from django import forms

from models import Pdf, Section, Subset
from forms import SectionAdminInlineForm

from django.contrib import messages


class SectionInline(admin.TabularInline):
    """
    Inline for sections
    """
    model = Section
    form  = SectionAdminInlineForm
    extra = 0

#class PdfAdminForm(forms.ModelForm):
#    def clean(self):
#        
#        cleaned_data = self.cleaned_data
#        
#        slugs=[v for k,v in cleaned_data.iteritems() if k.endswith("-slug")]
#        print cleaned_data.items()
#        sslugs = set(slugs)
#        print sslugs
#        if len(slugs) != len(sslugs):
#            raise forms.ValidationError('Duplicate slug field')
#        # Always return the full collection of cleaned data.
#        return cleaned_data
    
class PdfAdmin(admin.ModelAdmin):
    """
    ModelAdmin class for pdf. Allows to create sections. After save
    all sections are regenerated.
    """
    #form=PdfAdminForm
    list_display = ('name', 'slug', 'owner', 'admin_check_data', 
                    'admin_check_images', 'order')
    list_editable = ('order',)
    list_display_links = ['name', ]
    inlines = [SectionInline,]
    prepopulated_fields = {"slug": ("name",)}
    save_on_top = True
    
    class Media: # pylint: disable-msg=W0232,C0111,R0903
        js = (
            "binder/js/admin/base.js",
            "binder/js/admin/pdf_urlify.js",
            )

    def get_formsets(self, request, obj=None):
        """
        Check if section page images and pdf are at sync.
        """
        if obj:
            if not obj.check_images():
                messages.error(
                    request,
                    'Flip book images for %s are out of sync.' % obj.slug)
            if not obj.check_data():
                messages.error(
                    request,
                    'Data files for %s are out of sync.' % obj.slug)
        return super(PdfAdmin, self).get_formsets(request, obj=obj)

    def save_formset(self, request, form, formset, change):
        """
        Generate sections pdf.
        """
        super(PdfAdmin, self).save_formset(request, form, formset, change)
        #form.instance.generate_pdf_data()

    def get_object(self, request, object_id):
        """
        Save object for later.
        """
        self.object = super(PdfAdmin, self).get_object(request, object_id)
        return self.object
    
    def save_model(self, request, obj, form, change):
        """
        Update modification time when saved by admin - used by check_data and check_images.
        """
        obj.modified = datetime.datetime.now()
        obj.save()

    def admin_check_data(self, obj): # pylint: disable-msg=R0201
        """
        Check if generated images and pdfs are in sync.
        """
        return obj.check_data()
    
    def admin_check_images(self, obj): # pylint: disable-msg=R0201
        """
        Check if generated images and pdfs are in sync.
        """
        return obj.check_images()
    
    # pylint: disable-msg=W0612
    admin_check_data.short_description = 'Data Check' 
    admin_check_data.boolean = True
    admin_check_images.short_description = 'Image Check' 
    admin_check_images.boolean = True
    # pylint: enable-msg=W0612


class SectionAdmin(admin.ModelAdmin):
    """
    ModelAdmin class for sections.
    """
    list_display = ('id', 'pdf_name', 'name', 'order')
    list_display_links = ['name', ]
    ordering = ('pdf', 'id')
    list_filter = ('pdf',)
    
    def pdf_name(self, obj):
        """
        Returns pdf name
        """
        return obj.pdf.name


class SubsetAdmin(admin.ModelAdmin):
    """
    ModelAdmin class for subsets.
    """
    list_display = ('id', 'pdf_name', 'slug', 'get_section_count', 'get_page_count',)
    list_display_links = ['slug', ]
    ordering = ('pdf', 'id')
    list_filter = ('pdf',)
    filter_horizontal = ['sections']
    
    def pdf_name(self, obj):
        """
        Returns pdf name
        """
        return obj.pdf.name

        
    
admin.site.register(Pdf, PdfAdmin)
admin.site.register(Section, SectionAdmin)
admin.site.register(Subset, SubsetAdmin)
