import csv
import os
import shutil
import subprocess
import tempfile


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)
