
#
# See LICENCE for detail
# Copyright (c) 2014 IRI
#

import datetime
import json
import uuid

from sqlalchemy import (Column, Integer, String, DateTime, Text, Table, Index,
                        text, ForeignKey, Boolean)
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import func
from sqlalchemy.dialects.postgresql import UUID, JSON

from database import Base, engine


class Annotation(Base):
    __tablename__ = 'annotation'

    id = Column(Integer, primary_key=True, nullable=False)
    uuid = Column(UUID, unique=True, nullable=False)
    created = Column(DateTime, nullable=False, server_default=text("(now() at time zone 'utc')") )
    ts = Column(DateTime(timezone=True), nullable=False, index=True)
    event_code = Column(String(255), ForeignKey('event.code'), nullable=False, index=True)
    channel = Column(String(255), nullable=False, index=True)
    content = Column(JSON)


def insert_annot_async(params, conn):

    content = params.get('content', {})
    if not isinstance(content, basestring):
        params['content'] = json.dumps(content)
    if 'uuid' not in params:
        params['uuid'] = uuid.uuid4()

    if 'ts' not in params:
        params['ts'] = datetime.utcnow()

    stmt = Annotation.__table__.insert().values(**params).compile(engine)

    defer = conn.runOperation(stmt.string, stmt.params)
    defer.addCallback(lambda _: stmt.params)

    return defer


class Event(Base):
    __tablename__ = 'event'

    id = Column(Integer, primary_key=True, nullable=False)
    code = Column(String(255), unique=True, nullable=False, index=True)
    label = Column(String(2048), nullable=False)
    description = Column(Text(), nullable=True)
    start_date = Column(DateTime(), nullable=True, index=True)
    active = Column(Boolean(), nullable=False, default=True, server_default='1', index=True)

    sessions = relationship("EventSession", order_by="EventSession.order", backref="event")

    def __unicode__(self):
        return self.code

class EventSession(Base):
    __tablename__ = 'event_session'

    id = Column(Integer, primary_key=True, nullable=False)
    uuid = Column(UUID, unique=True, nullable=False, default=uuid.uuid4)
    label = Column(String(2048), nullable=True)
    event_id = Column(Integer, ForeignKey(Event.id), nullable=False)
    project_id = Column(String(2048), nullable=True)
    order = Column(Integer, nullable=False, default=0, index=True)
    start_ts = Column(DateTime(timezone=True), nullable=True, index=True)
    duration = Column(Integer, nullable=True)
    categories_json = Column(JSON, nullable=True)
