"""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:
        A connection 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:
        A list of the rows returned by Oracle. Each row is a tuple.

    """
    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.

    Returns:
        A list of tuples.
    """
    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)


# def get_all_magnets(facility):
#     # Create temporary csv file
#     temp_dir = tempfile.mkdtemp()
#     temp_csv_path = os.path.join(temp_dir, 'magnet_devices_oracle.csv')
#     os.environ['temp_csv_path'] = temp_csv_path
#
#     # Get data from Oracle
#     facility_filename_dict = {
#         'LCLS': 'AD_ACCEL',
#         'FACET': 'FACET2'
#     }
#     filename = facility_filename_dict[facility]
#     subprocess.check_output(['sqlplus', '/@SLACPROD', '@mgnt_get_magnets', filename])
#
#     # Read out elements
#     magnets = []
#     with open(temp_csv_path) as f:
#         reader = csv.reader(f)
#         for row in reader:
#             magnets.append(row)
#
#     shutil.rmtree(temp_dir)
#     return magnets

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