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

options_defaults['inheritance'] = 'multi'


class Page(Entity):
    """Page"""
    using_options(tablename='page',shortnames=True)
    title = Field(Unicode())
    slug = Field(String(255))
    content = Field(Unicode())
    published = Field(DateTime)
    display = Field(Boolean(), default=True)
    author = ManyToOne('{{package}}.model.identity.User')
    
    def __str__(self):
        return '%s' % self.slug.encode('utf8', 'xmlcharrefreplace')

    def __unicode__(self):
        return u'%s' % self.slug
    
    # 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}
    

class Author(Entity):
    """Author"""
    using_options(tablename='author',shortnames=True)
    name = Field(Unicode())
    initials = Field(Unicode())
    given_name = Field(Unicode())
    middle_initials = Field(Unicode())
    middle_name = Field(Unicode())
    family_name = Field(Unicode())
    
    def create(self, name, initials, given_name, middle_name, middle_initials, family_name):
        self.name = name.decode('utf8')
        self.initials = initials.decode('utf8')
        self.given_name = given_name.decode('utf8')
        self.middle_name = middle_name.decode('utf8')
        self.middle_initials = middle_initials.decode('utf8')
        self.family_name = family_name.decode('utf8')
    
    def __str__(self):
        return '%s' % self.name.encode('utf8', 'xmlcharrefreplace')
    
    def __unicode__(self):
        return u'%s' % self.name

class ChangelogItem(Entity):
    """ChangelogItem"""
    action = Field(Unicode(255))
    user = ManyToOne('{{package}}.model.identity.User')
    content = Field(Unicode())
    date = Field(DateTime)
    item = Field(String(255))
    refid = Field(Integer)
    using_options(tablename='changelog',order_by='date')
   
    def __str__(self):
        return '%s' % self.action.encode('utf8', 'xmlcharrefreplace')
    
    def __unicode__(self):
        return u'%s' % self.action
    

__all__=['Page','ChangelogItem', 'Author']
