from django.conf import settings
from django.contrib.admin import actions
from django.utils.translation import ugettext_lazy, ugettext as _
from feincms.admin import editor

"""
For this hack to work the django-mptt managers.py has to have been patched:
http://code.google.com/p/django-mptt/issues/detail?id=13
"""
def delete_selected_tree(modeladmin, request, queryset):
    return_val = actions.delete_selected(modeladmin, request, queryset)
    if return_val is None:
        # this means deletion was completed
        tree_manager = getattr(modeladmin.model._meta,'tree_manager_attr','tree')
        tree = getattr(modeladmin.model,tree_manager)
        tree.rebuild()
    return return_val

delete_selected_tree.short_description = ugettext_lazy("Delete selected %(verbose_name_plural)s")

class MPTTModelAdmin(editor.TreeEditor):
    # see: http://magicrebirth.wordpress.com/2009/08/18/django-admin-and-mptt-2/
    # this extends the method already found in (FeinCMS) TreeEditor class
    def _actions_column(self, obj):
        actions = super(MPTTModelAdmin, self)._actions_column(obj)
        actions.insert(0,
            u'<a title="%s" href="add/?%s=%s"><img src="%simg/admin/icon_addlink.gif" alt="%s" /></a>' % (getattr(self.model._meta,'parent_attr','parent'), obj.pk, 'Add child', settings.ADMIN_MEDIA_PREFIX, _('Add child'))
        )
        actions.insert(0,
            u'<a title="%s" href="%s" target="_blank"><img src="%simg/admin/selector-search.gif" alt="%s" /></a>' % (obj.get_absolute_url(), 'View on site', settings.ADMIN_MEDIA_PREFIX, _('View on site'))
        )
        return actions

    def get_actions(self, request):
        actions = super(MPTTModelAdmin, self).get_actions(request)
        actions['delete_selected'] = (delete_selected_tree, 'delete_selected', delete_selected_tree.short_description) # replace the default delete action
        return actions