from datetime import datetime

from peewee import (AutoField, BooleanField, DateTimeField, ForeignKeyField,
                    TextField, fn)
from playhouse.sqlite_ext import JSONField

from .base_model import BaseModel, db
from .recipes import Recipes
from .users import Users


class Autotests(BaseModel):
    id = AutoField(primary_key=True, unique=True, null=False)
    time = DateTimeField(unique=True, null=False, default=datetime.now)
    user = ForeignKeyField(Users, Users.username, null=False)
    recipe = ForeignKeyField(Recipes, null=False)
    result = BooleanField(null=False)
    overridden = BooleanField(null=False)
    reason = TextField(null=False)
    test_data = JSONField(null=False)

    @classmethod
    @db.atomic()
    def archive(cls, recipe, test_data, result, overridden, reason):
        return cls.create(
            user=Users.get_session().user,
            recipe=recipe,
            test_data=test_data,
            result=result,
            overridden=overridden,
            reason=reason,
        )

    @staticmethod
    def get_last_time():
        return Autotests.select(fn.MAX(Autotests.time)).scalar()

    class Meta:
        table_name = "autotests"
