from datetime import datetime

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

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


class Archive(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)
    result = BooleanField(null=False)
    overridden = BooleanField(null=False)
    test_data = JSONField(null=False)
    label = TextField(null=True)
    archived = BooleanField(null=False, default=False)
    uploaded = BooleanField(null=False, default=False)

    @classmethod
    @db.atomic()
    def archive(cls, recipe, test_data, result, overridden):
        # parsed_test_data = {
        #     "ESITO GLOBALE COLLAUDO": "OK" if test_data.get("ok", None) else "KO",
        #     "recipe": test_data.get("recipe", None),
        # }
        # total_duration = 0
        # for step_name in [
        #     "autotest",
        #     "barcodes",
        #     "connector",
        #     "leak",
        #     "print",
        #     "resistance",
        #     "vision",
        # ]:
        #     for k, v in test_data.get(step_name, {}).items():
        #         if step_name not in parsed_test_data:
        #             parsed_test_data[step_name] = {}
        #         parsed_test_data[step_name][k] = {
        #             f"ESITO {step_name}": "OK" if v.get("ok", None) else "KO",
        #             "result": v.get("results", {}).get("result", None),
        #             "data": v.get("results", {}).get("data", None),
        #             "step": v.get("step", None),
        #             "duration": v.get("duration", None),
        #         }
        #         if parsed_test_data[step_name][k]["duration"] is not None:
        #             total_duration += parsed_test_data[step_name][k]["duration"]
        # parsed_test_data["DURATA TOTALE COLLAUDO"] = total_duration
        return cls.create(
            user=Users.get_session().user,
            recipe=recipe,
            test_data=test_data,
            result=result,
            overridden=overridden,
        )

    class Meta:
        table_name = "archive"
