__author__ = 'RemiZOffAlex'
__email__ = 'remizoffalex@mail.ru'

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

from .. import Base


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

    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="PageTag.page_id==Page.id",
        uselist=False
    )
    tag = relationship(
        "Tag",
        primaryjoin="PageTag.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 "<PageTag('%s')>" % (self.id)

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