from datetime import datetime
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import relationship
from db import Base, CRUD
import utils


class Toolkit(Base):
    __tablename__ = "toolkits"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, unique=True, index=True)
    description = Column(Text, nullable=True)
    specifications = Column(JSONB, default={})
    category_id = Column(Integer, ForeignKey("categories.id", ondelete="CASCADE"))
    category_data = relationship(
        "Category",
        cascade="all, delete-orphan",
        lazy="joined",
        uselist=False,
        single_parent=True,
    )
    image = Column(JSONB)
    quantity_min = Column(Integer, nullable=True)
    quantity_min_extra = Column(Integer, nullable=True)
    external_link = Column(String, nullable=True)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    refilled_at = Column(DateTime, default=datetime.now)
    moved_at = Column(DateTime, default=datetime.now)

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

    def toDict(self):
        return utils.toDict(self)

    async def save(self):
        return await CRUD.create(self, refresh=True)

    async def edit(self, **kwargs):
        return await CRUD.update(Toolkit, self.id, **kwargs)
