__author__ = 'RemiZOffAlex'
__copyright__ = '(c) RemiZOffAlex'
__email__ = 'remizoffalex@mail.ru'

import datetime
from sqlalchemy import Column, Integer, ForeignKey, String, DateTime
from sqlalchemy.orm import relationship

from . import Base


class Page(Base):
    """Страницы
    """
    __tablename__ = "page"

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('user.id'))
    title = Column(String)
    body = Column(String, default='')
    created = Column(DateTime)  # Дата создания
    updated = Column(DateTime)  # Дата обновления

    # Связи
    user = relationship(
        "User",
        primaryjoin="Page.user_id==User.id",
        uselist=False
    )
    tags = relationship("TagPage", primaryjoin="Page.id==TagPage.page_id")

    def __init__(self, user, title):
        assert type(user).__name__ == 'User', 'Не передан объект User'
        self.user_id = user.id
        self.title = title
        self.created = datetime.datetime.now()
        self.updated = datetime.datetime.now()

    def __repr__(self):
        return "<Page('{}')>".format(self.title)

    def as_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}


class TagPage(Base):
    """Теги к страницам"""
    __tablename__ = "tagpage"

    id = Column(Integer, primary_key=True)
    page_id = Column(Integer, ForeignKey('page.id'))
    tag_id = Column(Integer, ForeignKey('tag.id'))
    created = Column(DateTime)  # Дата создания

    # Связи
    page = relationship(
        "Page",
        primaryjoin="TagPage.page_id==Page.id",
        uselist=False
    )
    tag = relationship(
        "Tag",
        primaryjoin="TagPage.tag_id==Tag.id",
        uselist=False
    )

    def __init__(self, page, tag):
        assert type(page).__name__ == 'Page', 'Не передан объект Page'
        assert type(tag).__name__ == 'Tag', 'Не передан объект Tag'
        self.page_id = page.id
        self.tag_id = tag.id
        self.created = datetime.datetime.now()

    def __repr__(self):
        return "<TagPage('%s')>" % (self.id)

    def as_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}
