from feincms.models import ContentProxy
from feincms.module.page.models import Page


class InheritLanguageContentProxy(ContentProxy):
    def get_content(self, item, attr):
        try:
            region = item.template.regions_dict[attr]
        except KeyError:
            return []

        def collect_items(obj):
            contents = obj._content_for_region(region)
            
            # if the obj is a translation of another object, try to get the content of it
            if region.inherited and not contents and hasattr(obj, 'translation_of_id') and obj.translation_of_id:
                return collect_items(obj.translation_of)
            # go to parent if this model has a parent attribute
            if region.inherited and not contents and hasattr(obj, 'parent_id') and obj.parent_id:
                return collect_items(obj.parent)

            return contents

        contents = collect_items(item)
        contents.sort(key=lambda c: c.ordering)
        return contents
Page.content_proxy_class = InheritLanguageContentProxy