"""
Models for sites.

:copyright: Copyright 2013-2016, Dorian Pula <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import uuid

import sqlalchemy
from sqlalchemy import orm
from sqlalchemy_utils.types import url as sql_url, uuid as sql_uuid

from rookeries import database


class Site(database.ModelBase):
    __tablename__ = 'site'

    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    api_key = sqlalchemy.Column(sql_uuid.UUIDType, unique=True, nullable=False)
    name = sqlalchemy.Column(sqlalchemy.String(64))
    url = sqlalchemy.Column(sql_url.URLType)

    # TODO: Add in tag line, copyright notice, favicon and logo image, other attributes in here.
    config = sqlalchemy.Column(sqlalchemy.JSON)

    def __init__(self, name, url, config=None, api_key=None):
        self.name = name
        self.url = url
        self.config = config or {}
        self.api_key = api_key or uuid.uuid4()

    def __repr__(self) -> str:
        return '<Site {!r} - {!r}>'.format(self.name, self.url)

    def to_json(self) -> dict:
        return {
            'api_key': self.api_key,
            'name': self.name,
            'url': self.url,
            'config': self.config,
        }


class SiteMenu(database.ModelBase):
    __tablename__ = 'site_menu'

    id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    orderinal = sqlalchemy.Column(sqlalchemy.Integer)
    title = sqlalchemy.Column(sqlalchemy.String)

    site_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey('site.id'))
    site = orm.relationship('Site', back_populates='menu')

    page_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey('page.id'))
    page = orm.relationship('Page')

    def __init__(self, title, site, page, orderinal=0):
        self.title = title
        self.site = site
        self.page = page
        self.orderinal = orderinal

    def __repr__(self) -> str:
        return '<SiteMenu {!r} - {!r}>'.format(self.orderinal, self.title)

    def to_json(self) -> dict:
        return {
            'title': self.title,
            'orderinal': self.orderinal,
            'page': self.page.slug,
            # TODO: Improve this into something more regular.
            'url': '/' + self.page.slug,
        }


Site.menu = orm.relationship(SiteMenu, order_by=SiteMenu.orderinal, back_populates="site")
