from django import forms
from django.conf import settings
from django.contrib.admin.widgets import AdminRadioSelect
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.db import models
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _

from feincms.admin.editor import ItemEditorForm
from feincms.module.medialibrary.models import MediaFile
from feincms.templatetags import feincms_thumbnail


class MediaFileWidget(forms.TextInput):
    """
    TextInput widget, shows a link to the current value if there is one.
    """

    def render(self, name, value, attrs=None):
        inputfield = super(MediaFileWidget, self).render(name, value, attrs)
        if value:
            try:
                mf = MediaFile.objects.get(pk=value)
                try:
                    caption = mf.translation.caption
                except ObjectDoesNotExist:
                    caption = _('(no caption)')

                if mf.type == 'image':
                    image = feincms_thumbnail.thumbnail(mf.file.name, '240x120')
                    image = u'<img src="%(url)s" alt="" /><br />' % {'url': image}
                else:
                    image = u''

                return mark_safe(u"""
                    <div style="margin-left:10em">%(image)s
                    <a href="%(url)s" target="_blank">%(caption)s (%(url)s)</a><br />
                    %(inputfield)s
                    </div>""" % {
                        'image': image,
                        'url': mf.file.url,
                        'caption': caption,
                        'inputfield': inputfield})
            except:
                pass

        return inputfield




# FeinCMS connector
class MediaFileContent(models.Model):
    feincms_item_editor_includes = {
        'head': ['admin/content/mediafile/init.html'],
        }

    class Meta:
        abstract = True
        verbose_name = _('media file')
        verbose_name_plural = _('media files')

    @classmethod
    def initialize_type(cls, POSITION_CHOICES=None, MEDIAFILE_CLASS=MediaFile):
        if 'feincms.module.medialibrary' not in settings.INSTALLED_APPS:
            raise ImproperlyConfigured, 'You have to add \'feincms.module.medialibrary\' to your INSTALLED_APPS before creating a %s' % cls.__name__

        if POSITION_CHOICES is None:
            raise ImproperlyConfigured, 'You need to set POSITION_CHOICES when creating a %s' % cls.__name__

        cls.add_to_class('mediafile', models.ForeignKey(MEDIAFILE_CLASS, verbose_name=_('media file'),
            related_name='%s_%s_set' % (cls._meta.app_label, cls._meta.module_name)
            ))

        cls.add_to_class('position', models.CharField(_('position'),
            max_length=10, choices=POSITION_CHOICES,
            default=POSITION_CHOICES[0][0]))

        class MediaFileContentAdminForm(ItemEditorForm):
            mediafile = forms.ModelChoiceField(queryset=MEDIAFILE_CLASS.objects.all(),
                widget=MediaFileWidget)
            position = forms.ChoiceField(choices=POSITION_CHOICES,
                initial=POSITION_CHOICES[0][0], label=_('position'),
                widget=AdminRadioSelect(attrs={'class': 'radiolist'}))

        cls.feincms_item_editor_form = MediaFileContentAdminForm

    def render(self, **kwargs):
        request = kwargs.get('request')
        return render_to_string([
            'content/mediafile/%s_%s.html' % (self.mediafile.type, self.position),
            'content/mediafile/%s.html' % self.mediafile.type,
            'content/mediafile/%s.html' % self.position,
            'content/mediafile/default.html',
            ], { 'content': self, 'request': request })


    @classmethod
    def default_create_content_type(cls, cms_model):
        return cms_model.create_content_type(cls, POSITION_CHOICES=(
            ('block', _('block')),
            ('left', _('left')),
            ('right', _('right')),
            ))

@@ -799,37 +799,16 @@
  value:%0A
-            try:%0A    
         
@@ -860,20 +860,16 @@
         
-    
 try:%0A   
@@ -873,36 +873,32 @@
                 
-  
-  
 caption = mf.tra
@@ -922,28 +922,24 @@
             
-    
 except Objec
@@ -961,36 +961,32 @@
                 
-  
-  
 caption = _('(no
@@ -1010,20 +1010,16 @@
         
-    
 if mf.ty
@@ -1041,36 +1041,32 @@
                 
-   
- 
 image = feincms_
@@ -1110,20 +1110,16 @@
 0x120')%0A
-    
         
@@ -1189,20 +1189,16 @@
  image%7D%0A
-    
         
@@ -1215,36 +1215,32 @@
                 
-    
 image = u''%0A%0A   
@@ -1236,20 +1236,16 @@
  = u''%0A%0A
-    
         
@@ -1286,20 +1286,16 @@
         
- 
-   
 %3Cdiv sty
@@ -1326,20 +1326,16 @@
 image)s%0A
-    
         
@@ -1392,17 +1392,17 @@
 n)s 
-(
+- 
 %25(url)s
-)
 %3C/a%3E
@@ -1408,20 +1408,16 @@
 %3E%3Cbr /%3E%0A
-    
         
@@ -1455,20 +1455,16 @@
         
-  
-  
 %3C/div%3E%22%22
@@ -1469,20 +1469,16 @@
 %22%22%22 %25 %7B%0A
-    
         
@@ -1525,20 +1525,16 @@
         
-   
- 
 'url': m
@@ -1545,20 +1545,16 @@
 le.url,%0A
-    
         
@@ -1581,28 +1581,24 @@
 ': caption,%0A
-    
             
@@ -1635,49 +1635,8 @@
 ld%7D)
-%0A            except:%0A                pass
 %0A%0A  
@@ -1661,18 +1661,16 @@
 field%0A%0A%0A
-%0A%0A
 # FeinCM

Clean up error checking on MediaItem render