# -*- coding: utf-8 -*-

from datetime import datetime
from sqlalchemy import Column, ForeignKey, Sequence
from sqlalchemy import DateTime, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()


def create_all():
    from application import SQLALCHEMY_DATABASE_URI
    from sqlalchemy import create_engine
    Base.metadata.create_all(create_engine(SQLALCHEMY_DATABASE_URI))


def drop_all():
    from application import SQLALCHEMY_DATABASE_URI
    from sqlalchemy import create_engine
    Base.metadata.drop_all(create_engine(SQLALCHEMY_DATABASE_URI))


class List(Base):
    __tablename__ = 'lists'

    id = Column(Integer, Sequence('list_id_seq'), primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    title = Column(String(4096), unique=True, nullable=False)
    rck = Column(String(64), nullable=True, default=None)

    user = relationship('User', back_populates='lists')
    tasks = relationship('Task', back_populates='list',
        cascade='all, delete, delete-orphan')


class Task(Base):
    __tablename__ = 'tasks'

    id = Column(Integer, Sequence('task_id_seq'), primary_key=True)
    list_id = Column(Integer, ForeignKey('lists.id'), nullable=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=True)
    date135 = Column(String(10), nullable=True)
    priority = Column(Integer, nullable=True)
    title = Column(String(4096), nullable=False)
    rck = Column(String(64), nullable=False)
    state = Column(String(16), nullable=False)
    create_ts = Column(DateTime(), nullable=False, default=datetime.utcnow)
    update_ts = Column(DateTime(), nullable=False, default=datetime.utcnow)

    list = relationship('List', back_populates='tasks')
    user = relationship('User', back_populates='tasks')


class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    name = Column(String(64), unique=True, nullable=False)
    hash = Column(String(64), unique=True, nullable=False)
    salt = Column(String(64), unique=True, nullable=False)
    color = Column(String(16), nullable=False, default='#A00')
    fails = Column(Integer, default=0)

    lists = relationship('List', back_populates='user')
    tasks = relationship('Task', back_populates='user')
