from cubicweb_web.views.urlrewrite import SimpleReqRewriter, rgx


class BlogReqRewriter(SimpleReqRewriter):
    rules = [
        # links generated by archives by date/author boxes
        (rgx(r'/(micro)?blog/([0-9]+)/blogentries'),
         dict(rql='Any B,BD ORDERBY BD DESC WHERE B creation_date BD, '
                  'B entry_of BL, BL eid %(eid)s' % {'eid': r'\2'},
              )),
        (rgx(r'/(micro)?blog/([0-9]+)/blogentries/([a-z_]+)'),
         dict(rql='Any B,BD ORDERBY BD DESC WHERE B creation_date BD, '
                  'B entry_of BL, BL eid %(eid)s, '
                  'B created_by U, U login "%(user)s"' % {'eid': r'\2', 'user': r'\3'},
              user=r'\2')),
        (rgx(r'/(micro)?blog/([0-9]+)/blogentries/([0-9]{4})'),
         dict(rql='Any B,BD ORDERBY BD DESC WHERE B creation_date BD, B entry_of BL, BL eid %(eid)s'
              'HAVING YEAR(BD)= %(year)s' % {'eid': r'\2', 'year': r'\3'},
              )),
        (rgx(r'/(micro)?blog/([0-9]+)/blogentries/([0-9]{4})/([0-9]{2})'),
         dict(rql='Any B,BD ORDERBY BD DESC WHERE B creation_date BD, '
                  'B entry_of BL, BL eid %(eid)s '
                  'HAVING YEAR(BD)= %(year)s, MONTH(BD)=%(month)s' % {'eid': r'\2',
                                                                      'year': r'\3',
                                                                      'month': r'\4'},
              )),

        # XXX use or kill
        (rgx(r'/blogentry/([a-z_]+)'),
         dict(rql='Any B,BD ORDERBY BD DESC WHERE B is BlogEntry, '
                  'B creation_date BD, B created_by U, U login "%(user)s"' % {'user': r'\1'},
              user=r'\1')),
        (rgx(r'/blogentry/([a-z_]+)\.rss'),
         dict(rql='Any B,BD ORDERBY BD DESC LIMIT 20 WHERE B is BlogEntry, '
                  'B creation_date BD, B created_by U, U login "%(user)s"' % {'user': r'\1'},
              vid='rss')),


        (rgx(r'/blogentries/([0-9]{4})'),
         dict(rql='Any B,BD ORDERBY BD DESC WHERE B is BlogEntry, B creation_date BD '
                  'HAVING YEAR(BD) = %(year)s' % {'year': r'\1'})),
        (rgx(r'/blogentries/([0-9]{4})/([0-9]{2})'),
         dict(rql='Any B,BD ORDERBY BD DESC WHERE B is BlogEntry, B creation_date BD '
                  'HAVING YEAR(BD) = %(year)s, MONTH(BD) = %(month)s' % {'year': r'\1',
                                                                         'month': r'\2'})),

    ]
