# -*- coding: utf-8 -*-
from datetime import datetime
from elixir import *
from elixir import events
import hashlib
from pylons import url
from {{package}}.model import Session, metadata

options_defaults['inheritance'] = 'multi'

import re
import sets
from docutils.core import publish_parts
import {{package}}.lib.helpers as h
wikiwords = re.compile(r"\b([A-Z]\w+[A-Z]+\w+)", re.UNICODE)

class Page(Entity):
    title = Field(Unicode, primary_key=True)
    content = Field(Unicode, default='')
    using_options(tablename='page',shortnames=True)
    
    
    def __repr__(self):
        return "<Page: %r>" % self.title
    
    def __str__(self):
        return self.title
        
    def get_wiki_content(self):
        content = publish_parts(self.content, writer_name="html")["html_body"]
        titles = sets.Set(wikiwords.findall(content))
        for title in titles:
            title_url = url(controller='page', action='index',
                                  title=title)
            content = content.replace(title, h.link_to(title, title_url))
        return content

    # Borrowed from tw.dynforms
    @classmethod
    def text_search(cls, search):
        return cls.query.filter(cls.title.like('%'+search+'%'))

    def __json__(self):
        return {'id': self.id, 'value':self.title}

