from load.projects.cloud.loadtesting.db.tables import StorageTable
from load.projects.cloud.loadtesting.logan import lookup_logger

from sqlalchemy.orm import Query


class StorageQueries:
    def __init__(self, session):
        self._session = session

    def add(self, storage):
        self._session.add(storage)
        lookup_logger().debug(f"Create storage: {storage}")

    def delete(self, storage):
        self._session.delete(storage)
        lookup_logger().debug(f"Delete storage: {storage.id}")

    def get(self, storage_id) -> StorageTable:
        return self._session.query(StorageTable).filter(StorageTable.id == storage_id).first()

    def get_by_bucket(self, bucket, folder_id) -> StorageTable:
        return self._session.query(StorageTable).filter(StorageTable.bucket == bucket, StorageTable.folder_id == folder_id).first()

    def get_by_folder(self, folder_id, offset=None, limit=None):
        query: Query = self._session.query(StorageTable).filter(
            StorageTable.folder_id == folder_id).order_by(StorageTable.created_at.desc())
        if offset is not None:
            query = query.offset(offset)
        if limit is not None:
            query = query.limit(limit)
        return query.all()
