from datetime import datetime
from sqlalchemy import Column, DateTime, Float, ForeignKey, Integer, String
from sqlalchemy.orm import relationship

from db import Base, CRUD
import utils


class Stock(Base):
    __tablename__ = "stocks"

    id = Column(Integer, primary_key=True, index=True)
    toolkit_id = Column(
        Integer, ForeignKey("toolkits.id", ondelete="CASCADE"), nullable=False
    )
    toolkit_data = relationship(
        "Toolkit",
        cascade="all, delete-orphan",
        lazy="joined",
        uselist=False,
        single_parent=True,
    )
    toolbox_id = Column(
        Integer, ForeignKey("toolboxes.id", ondelete="CASCADE"), nullable=False
    )
    toolbox_data = relationship(
        "Toolbox",
        cascade="all, delete-orphan",
        lazy="joined",
        uselist=False,
        single_parent=True,
    )
    quantity = Column(Integer, nullable=False)
    price = Column(Float, nullable=False)
    placement = Column(String, nullable=True)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=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(Stock, self.id, **kwargs)
