import datetime

from lp_queue import db
from sqlalchemy.dialects.postgresql import JSONB, ENUM
import enum


class Status(enum.Enum):
    ENQUEUED = 'enqueued'
    CLAIMED = 'claimed'
    FINISHED = 'finished'


class Task(db.Model):
    __tablename__ = 'task'

    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(ENUM(Status), default=Status.ENQUEUED)
    claimed_by = db.Column(db.Text)  # tank_name
    configinitial = db.Column(JSONB, default={})
    config = db.Column(JSONB, default={})
    demands = db.Column(JSONB, default={})
    author = db.Column(db.String(128), nullable=True, default=None)
    enqueued_at = db.Column(db.DateTime, default=datetime.datetime.utcnow())
    claimed_at = db.Column(db.DateTime, nullable=True, default=None)
    finished_at = db.Column(db.DateTime, nullable=True, default=None)
    return_code = db.Column(db.SmallInteger, nullable=True, default=None)

    def __repr__(self):
        return f'<lp_queue_task: {self.status}>'

    def as_dict(self):
        return {
            'id': self.id,
            'status': self.status.value if self.status is not None else None,
            'tank_name': self.claimed_by,
            'config': self.config,
            'author': self.author,
        }


# TODO: upload token


class DefaultConfig(db.Model):
    __tablename__ = 'default_configs'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))
    content = db.Column(db.Text)



BDK_LOGS_CLICKHOUSE_DATABASE = '''
CREATE TABLE IF NOT EXISTS logs (key_date Date, job_id String, ts Int64, value String) ENGINE = MergeTree(key_date, job_id, (job_id, ts), 8192);
CREATE TABLE IF NOT EXISTS logs_buffer AS logs ENGINE = Buffer(bdk, logs, 16, 10, 100, 10000, 1000000, 10000000, 20000000);
'''