"""Utility functions for Oracle.

This file contains functions for retrieving data from Oracle, specifically the elements database, magnet polynomial
database, additional data, and SCORE.
"""

import os

import cx_Oracle


def connect(wallet, user):
    """Connects to Oracle.

    Args:
        wallet (str): The Oracle wallet, which contains credentials.
        user (str): The username of the Oracle database.

    Returns:
        cx_oracle.Connection: An object on which one can execute Oracle queries.
    """
    # If on dev, use afs directories
    wallet_dir = '/usr/local/lcls/tools/oracle/wallets'
    if not os.path.isdir(wallet_dir):
        wallet_dir = '/afs/slac/g/lcls/tools/oracle/wallets'
        os.environ['ORACLE_HOME'] = '/afs/slac/g/lcls/package/oracle/product/11.2.0.4/linux-x86_64'

    else:
        os.environ['ORACLE_HOME'] = '/usr/local/lcls/package/oracle/product/11.2.0.4/linux-x86_64'

    os.environ['TNS_ADMIN'] = os.path.join(wallet_dir, wallet)
    os.environ['TWO_TASK'] = user
    con = cx_Oracle.connect('/@' + user)
    return con


def run_query(wallet, user, query, **kwargs):
    """Executes a query on Oracle.

    Args:
        wallet (str): The Oracle wallet, which contains credentials.
        user (str): The username of the Oracle database.
        query (str): The SQL query.
        **kwargs: Optional keyword arguments for variable binding.

    Returns:
        list[tuple]: The rows returned by Oracle.
    """
    con = connect(wallet, user)
    cur = con.cursor()
    cur.execute(query, **kwargs)
    res = cur.fetchall()
    cur.close()
    con.close()
    return res


def get_all_magnets(facility):
    """Returns the polynomial and additional data for all magnets.

    Args:
        facility (str): Specific facility from which to get magnet data, either `LCLS` or `FACET`.

    Returns:
        list[tuple]: Magnet data from polynomial and additional data databases.
    """
    wallet = 'lcls_read'
    user = 'SLACPROD'
    sql_script_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mgnt_get_magnets.sql')
    with open(sql_script_path) as f:
        query = f.read()

    facility_to_beamline = {'LCLS': 'AD_ACCEL', 'FACET': 'FACET2'}
    beamline = facility_to_beamline[facility]
    return run_query(wallet, user, query, beamline=beamline)


if __name__ == '__main__':
    elements = get_all_magnets('LCLS')
    for element in elements:
        print(element)
