from db import db

class StoreModel(db.Model):

    __tablename__ = 'stores'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

    #identifies relationship with ItemModel
    #because there could be many ItemModel items, it knows that this could contain a bunch of stuff.
    #lazy only works if .all() is incorporated into the json method.
    #this means that it only digs into the db when json is called.
    items = db.relationship('ItemModel', lazy='dynamic')

    def __init__(self, name):
        self.name = name

    def json(self):
        return {'name': self.name, 'items': [item.json() for item in self.items.all()]}

    @classmethod
    def find_by_name(cls, name):
        #create an item model within items where name is equal to variable name
        return cls.query.filter_by(name=name).first() #selecting first oonly
              
#this upserts or updates and or inserts to the database
#so we combined the insert and update              
    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()

