from peewee import (
    Model,
    MySQLDatabase,
    AutoField,
    IntegerField,
    CharField,
    TextField,
    ForeignKeyField,
    DateTimeField,
    DoubleField,
    BooleanField,
)
import datetime
import sys, os
import myfab.log as log
from playhouse.shortcuts import ReconnectMixin

CONNECTION = None

class ReconnectMySQLDatabase(ReconnectMixin, MySQLDatabase):
    pass


def create_mysql_connection() -> MySQLDatabase:
    global CONNECTION

    assert CONNECTION == None
    if not "MYSQL_HOST" in os.environ:
        os.environ["MYSQL_HOST"] = "127.0.0.1"
        os.environ["MYSQL_DB"] = "db"
        os.environ["MYSQL_USER"] = "user"
        os.environ["MYSQL_PASSWORD"] = "password"
        log.warn("No MYSQL_HOST, using default values")

    url = os.environ["MYSQL_HOST"]
    log.info("Using MYSQL_HOST %s" % url)
    return ReconnectMySQLDatabase(
        os.environ["MYSQL_DB"],
        user=os.environ["MYSQL_USER"],
        host=url,
        password=os.environ["MYSQL_PASSWORD"],
        port=3306,
    )


def init_db_connection():
    db = create_mysql_connection()
    db.connect()
    tables = [User, PrintRequest, Event, Queue, QueueElement, Printer, PrinterQueue]
    db.bind(tables)
    db.create_tables(tables)


class User(Model):
    username = CharField(primary_key=True)
    fullname = CharField()
    access = IntegerField(default=0)


class Queue(Model):
    id = AutoField(primary_key=True)
    enabled = BooleanField()
    name = CharField()
    weight = IntegerField(default=1)
    meta = TextField()  # json


class QueueElement(Model):
    id = AutoField()
    state = IntegerField(default=0)  # 0: todo, 1: done, 2: err/ canceled ?
    queue = ForeignKeyField(Queue)
    time_added = DateTimeField(default=datetime.datetime.now())


class PrintRequest(Model):
    id = AutoField(primary_key=True)
    title = CharField()
    description = TextField()
    creation = DateTimeField(default=datetime.datetime.now(), column_name="creation")
    last_modification = DateTimeField(
        default=datetime.datetime.now(), column_name="last_modification"
    )
    author = ForeignKeyField(User)
    reject_message = CharField()
    stl = TextField(null=True, default=None)
    gcode = TextField(null=True, default=None)
    status = IntegerField(default=0)
    project = TextField()
    operator = ForeignKeyField(User, null=True, default=None)
    queue_element = ForeignKeyField(
        QueueElement, null=True, default=None
    )  # Only the queue info, the actual queue is not store in db
    recup_id = CharField(default="")


class Message(Model):
    id = AutoField(primary_key=True)
    author = ForeignKeyField(User, null=False)
    text = TextField()
    creation = DateTimeField(default=datetime.datetime.now, column_name="creation")
    request = ForeignKeyField(PrintRequest)
    read = BooleanField(default=False)


class Event(Model):  # to form timeline
    request = ForeignKeyField(PrintRequest)
    description = CharField()
    date = DateTimeField(default=datetime.datetime.now)
    operartor = ForeignKeyField(User, null=True, default=None)


class Printer(Model):  # with connection information
    id = AutoField()
    name = CharField()
    model = CharField()
    enabled = BooleanField(default=True)
    config = CharField()  # json
    current_print = ForeignKeyField(PrintRequest, null=True)


class PrinterQueue(Model):
    printer = ForeignKeyField(Printer)
    queue = ForeignKeyField(Queue)


# V2, Slicer vm info ? maybe not even necessary
# class Slicer:
#     pass
