from app.db import db


# Ignore it if db can't find the row when updating/deleting
# Todo: not ignore it, raise some error, remove checkers in view
class BaseService:
    __abstract__ = True
    model = None

    # Create
    def add_one(self, **kwargs):
        new_row = self.model(**kwargs)
        db.session.add(new_row)
        db.session.commit()  # sqlalchemy auto flushes so maybe this just need commit ?

        return new_row

    # Read
    def select_one(self, id):
        return self.model.query.filter(self.model.id == id).one_or_none()

    def select_all(self, conditions: list = None, sort_by=None, is_asc=None):
        query = db.session.query(self.model)

        if conditions is not None:
            for condition in conditions:
                query = query.filter(condition)

        if sort_by is not None and is_asc is not None:
            sort_column = self.model.__table__._columns[sort_by]
            is_asc = is_asc == 'true'

            if sort_column is not None:
                query = query.order_by(sort_column.asc() if is_asc else sort_column.desc())

        return query.all()

    # Update
    def update_one(self, id, updated):
        row = self.model.query.filter(self.model.id == id)
        row_result = row.one_or_none()

        if row_result is not None:
            row.update(updated)
            db.session.commit()

            return row.one_or_none()

    # Delete
    def delete_one(self, id):
        row = self.select_one(id)

        if row is not None:
            db.session.delete(row)
            db.session.commit()

[((303, 326), 'app.db.db.session.add', 'db.session.add', (['new_row'], {}), '(new_row)\n', (317, 326), False, 'from app.db import db\n'), ((335, 354), 'app.db.db.session.commit', 'db.session.commit', ([], {}), '()\n', (352, 354), False, 'from app.db import db\n'), ((650, 678), 'app.db.db.session.query', 'db.session.query', (['self.model'], {}), '(self.model)\n', (666, 678), False, 'from app.db import db\n'), ((1355, 1374), 'app.db.db.session.commit', 'db.session.commit', ([], {}), '()\n', (1372, 1374), False, 'from app.db import db\n'), ((1532, 1554), 'app.db.db.session.delete', 'db.session.delete', (['row'], {}), '(row)\n', (1549, 1554), False, 'from app.db import db\n'), ((1567, 1586), 'app.db.db.session.commit', 'db.session.commit', ([], {}), '()\n', (1584, 1586), False, 'from app.db import db\n')]