import datetime

from sqlalchemy.orm import Query

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


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

    def add(self, operation):
        self._session.add(operation)
        lookup_logger().debug(f"Insert operation: {operation}")

    def get(self, operation_id):
        operation = self._session.query(OperationTable).filter(OperationTable.id == operation_id).first()
        lookup_logger().debug(f"Get operation from DB: {operation}")
        return operation

    def get_by_folder(self, folder_id, offset=None, limit=None):
        query: Query = self._session.query(OperationTable).filter(OperationTable.folder_id == folder_id).order_by(OperationTable.created_at.desc())
        if offset is not None:
            query = query.offset(offset)
        if limit is not None:
            query = query.limit(limit)
        result = query.all()
        lookup_logger().debug("Get operations list from DB: %s", result)
        return result

    def get_by_target_id(self, target_resource_id, done=False):
        return self._session.query(OperationTable).filter(
            OperationTable.target_resource_id == target_resource_id,
            OperationTable.done == done
        ).all()

    def update(self, operation, error=None, modified_at=None, done=True):
        if error is not None:
            operation.error = error
        operation.modified_at = modified_at or datetime.datetime.utcnow()
        operation.done = done
        lookup_logger().debug("Update operation: %s", operation)

    def add_snapshot(self, operation, snapshot):
        operation.done_resource_snapshot = snapshot
        lookup_logger().debug(f"Add resource snapshot for operation: {operation}")
