import json
from uuid import uuid4 as uuid

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

from .base_model import BaseModel
from ...helpers.step import Step


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)
    description = TextField(null=True)
    archived = BooleanField(null=False, default=False)

    def get_steps(self):
        steps = []
        for step_name, enabled in self.spec.items():
            if enabled in (True, 1):
                steps.append(Step(step_type=step_name,spec=self.spec["steps"][step_name]))
        return steps

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

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

    class Meta:
        table_name = "recipes"
