from uuid import uuid4 as uuid

from peewee import BooleanField, TextField
from playhouse.sqlite_ext import JSONField

from .base_model import BaseModel
from .steps import Steps


class Recipes(BaseModel):
    name = TextField(primary_key=True, unique=True, null=False, default=lambda: uuid().hex)
    client = TextField(null=True)
    part_number = TextField(null=False)
    spec = JSONField(null=False)  # keys inside spec must not overlap withthe model
    description = TextField(null=True)
    archived = BooleanField(null=False, default=False)

    def get_steps(self):
        steps = []
        for step_pk in self.spec.get("steps", []):
            steps.append(Steps.get_by_id(step_pk))
        return steps

    def delete_associated_steps(self):
        return Steps.delete().where(Steps._meta.primary_key << list(self.spec.get("available_steps", {}).values())).execute()

    def get_steps_map(self):
        steps = {}
        for step_name, step_pk in self.spec.get("available_steps", {}).items():
            steps[step_name] = Steps.get_by_id(step_pk)
        return steps

    @classmethod
    def crud_delete(cls, deleted_rows):
        # return cls.delete().where(self._meta.primary_key << deleted_rows).execute()
        recipes = list(cls.select().where(cls._meta.primary_key << deleted_rows).execute())
        for recipe in recipes:
            recipe.delete_associated_steps()
            recipe.delete_instance()
        return len(recipes)

    # @classmethod
    # def delete(cls, *args, **kwargs):
    #     # OVERRIDE DELETION
    #     # so that deleting a user will only archive it
    #     return cls.update(archived=True)

    class Meta:
        table_name = "recipes"
