# encoding: utf-8

import uuid
from sqlalchemy.sql import func
from sqlalchemy.dialects.postgresql import UUID
from chaos import db
from chaos.models import Client
from chaos.utils import get_current_time, paginate
from chaos.exceptions import ObjectUnknown

class Draft(db.Model):
    __tablename__ = 'draft'
    id = db.Column(UUID, primary_key=True)
    type = db.Column(db.Text, nullable=True)
    client_id = db.Column(UUID, db.ForeignKey(Client.id), nullable=False)
    data = db.Column(db.Text, unique=False, nullable=False)
    created_at = db.Column(db.DateTime(), server_default=db.func.now(), nullable=False)
    updated_at = db.Column(db.DateTime(), default=None, onupdate=get_current_time)

    def __init__(self):
        self.id = str(uuid.uuid1())

    @classmethod
    def get(cls, id, client_id):
        return cls.query.filter_by(id=id, client_id=client_id).first_or_404()

    @classmethod
    @paginate()
    def all(cls, client_id, type):
        query = cls.query.filter_by(type=type)
        query = query.join(Client)
        return  query.filter(Client.id == client_id)
