# copyright 2015 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr -- mailto:contact@logilab.fr
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
"""cubicweb-seda views for archive unit components"""

from cubicweb.predicates import (is_instance, multi_lines_rset,
                                 has_related_entities, relation_possible)
from cubicweb.web.views import basecomponents, baseviews, ibreadcrumbs, urlrewrite


class SEDAReqRewriter(urlrewrite.SimpleReqRewriter):
    ignore_baseclass_rules = True
    rules = [
        ('/sedalib', dict(rql='Any X WHERE X is SEDAArchiveUnit, '
                              'NOT X seda_archive_unit P',
                          vid='seda.sedalib')),
    ]


# navigation #######################################################################################

class SEDAComponentsBreadcrumbsAdapter(ibreadcrumbs.IBreadCrumbsAdapter):
    """Breadcrumbs adapter pointing to /sedalib route when entity has no
    parent.
    """
    __select__ = (ibreadcrumbs.IBreadCrumbsAdapter.__select__
                  & relation_possible('seda_archive_unit', role='subject')
                  & ~has_related_entities('seda_archive_unit', role='subject'))

    def breadcrumbs(self, *args, **kwargs):
        return [(self._cw.build_url('sedalib'), self._cw._('SEDAArchiveUnit_plural')),
                self.entity]


class SEDAComponentsBreadCrumbETypeVComponent(ibreadcrumbs.BreadCrumbEntityVComponent):
    """For proper display of the breadcrumb in the SEDA components list"""
    __select__ = (basecomponents.HeaderComponent.__select__
                  & multi_lines_rset() & is_instance('SEDAArchiveUnit'))

    def render_breadcrumbs(self, w, contextentity, path):
        w(u'<a href="%s">%s</a>' % (self._cw.build_url('sedalib'),
                                    self._cw._('SEDAArchiveUnit')))


# SEDA lib components ##############################################################################

class SEDALibView(baseviews.SameETypeListView):
    __regid__ = 'seda.sedalib'
    __select__ = is_instance('SEDAArchiveUnit')

    @property
    def title(self):
        return self._cw._('SEDAArchiveUnit_plural')
