"""Database support module for the benchbuild study."""
import logging

from sqlalchemy.exc import IntegrityError

from benchbuild.settings import CFG

LOG = logging.getLogger(__name__)


def validate(func):

    def validate_run_func(run, session, *args, **kwargs):
        if run.status == 'failed':
            LOG.debug("Run failed. Execution of '%s' cancelled", str(func))
            return None

        return func(run, session, *args, **kwargs)

    return validate_run_func


def create_run(cmd, project, exp, grp):
    """
    Create a new 'run' in the database.

    This creates a new transaction in the database and creates a new
    run in this transaction. Afterwards we return both the transaction as
    well as the run itself. The user is responsible for committing it when
    the time comes.

    Args:
        cmd: The command that has been executed.
        prj: The project this run belongs to.
        exp: The experiment this run belongs to.
        grp: The run_group (uuid) we blong to.

    Returns:
        The inserted tuple representing the run and the session opened with
        the new run. Don't forget to commit it at some point.
    """
    from benchbuild.utils import schema as s

    session = s.Session()
    run = s.Run(command=str(cmd),
                project_name=project.name,
                project_group=project.group,
                experiment_name=exp.name,
                run_group=str(grp),
                experiment_group=exp.id)
    session.add(run)