from __future__ import print_function

import csv
import fnmatch
import getpass
import os
import shutil
import subprocess
import tempfile
from collections import OrderedDict
from decimal import Decimal, ROUND_HALF_UP
from math import floor, log10, isnan

import numpy as np
from six import itervalues
from six.moves import input

magnets = {}
facility = ''
json_dir = ''
results = {}
enable_writes = True
warned_about_writes = False
read_only = False
verbose = False

facility_to_beamline = {
    None: 'AD_ACCEL',
    'LCLS': 'AD_ACCEL',
    'FACET': 'FACET2'
}


def verbose_print(*args, **kwargs):
    if verbose:
        print(*args, **kwargs)


def init(fac, json_d, csv_file, verb):
    # Preload all magnets
    global magnets, facility, verbose
    facility = fac
    json_dir = json_d
    verbose = verb
    magnets = get_magnets(csv_file)


def to_float(x):
    try:
        return float(x)
    except (ValueError, TypeError):
        return float('nan')


def get_magnets(csv_file, allowed_areas=(
        'L0B', 'HTR', 'COL0', 'DIAG0', 'L1B', 'BC1B', 'COL1', 'L2B', 'BC2B', 'EMIT2', 'L3B', 'EXT', 'DOG', 'BYP', 'SPH',
        'SLTH', 'SPS', 'SLTS', 'SPD', 'SLTD'), excluded_elements=('QCM34')):
    if csv_file:
        return get_magnets_from_csv(csv_file, allowed_areas, excluded_elements)

    return get_magnets_from_oracle(allowed_areas, excluded_elements)


def get_magnets_from_csv(csv_file, allowed_areas, excluded_elements):
    # Read out elements
    magnets = OrderedDict()
    with open(csv_file) as f:
        reader = csv.reader(f)
        for row in reader:
            if row[0] not in excluded_elements:
                # if row[2] in allowed_areas and row[0] not in excluded_elements:
                magnets[row[0]] = {
                    'element': row[0],
                    'barcode': row[1],
                    'area': row[2],
                    'device': row[3],
                    'z_pos': to_float(row[4]),
                    'keyword': 'SOLN' if row[5] == 'SOLE' else row[5],
                    'op_status': row[6],
                    'psc_type': row[7],
                    'psc_device': row[8].upper(),
                    'acsw_node': row[9],
                    'ts_node': row[10].split(':')[0],
                    'ts_port': row[10].split(':')[-1],
                    'crate_num': row[11],
                    'bulk_ps': row[12],
                    'ioc': row[13],
                    'sw_ps_string': row[14],
                    'acsw_name': row[9].split(':')[0].upper().replace('-', ':'),
                    'acsw_host': row[9].split(':')[0],
                    'acsw_plug': row[9].split(':')[-1],
                    'loca': row[18],
                    'degaus_enable': 0 if row[19] == 'DISABLED' else 1,
                    'degausramprate': to_float(row[20]),
                    'degaussetl': to_float(row[21]),
                    'degauswf': np.array([to_float(i) for i in row[22].split(',')]),
                    'ps_string': row[23],
                    'ps_config': row[24].title(),
                    'imin': to_float(row[25]),
                    'imax': to_float(row[26]),
                    'bmin': to_float(row[27]),
                    'bmax': to_float(row[28]),
                    'stdz_disable': 1 if row[29] == 'DISABLED' else 0,
                    'stdzcyclenum': to_float(row[30]),
                    'stdzimin': to_float(row[31]),
                    'stdzimax': to_float(row[32]),
                    'stdzifinal': to_float(row[33]),
                    'trimramprate': to_float(row[34]),
                    'trimsetl': to_float(row[35]),
                    'ivb': row[36:]
                }

    return magnets


def get_magnets_from_oracle(allowed_areas, excluded_elements):
    # Create temporary csv file
    temp_dir = tempfile.mkdtemp()
    temp_csv_path = os.path.join(temp_dir, 'mgnt_devices_oracle.csv')

    # Get beamline from facility
    beamline = facility_to_beamline[facility]

    # Get data from Oracle
    sql_script_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'mgnt_get_magnets.sql')
    subprocess.check_output(['sqlplus', '/@SLACPROD', '@' + sql_script_path, temp_csv_path, beamline])

    # Read out elements
    oracle_magnets = get_magnets_from_csv(temp_csv_path, allowed_areas, excluded_elements)
    shutil.rmtree(temp_dir)
    return oracle_magnets


def get_all_magnets():
    return magnets


def get_wild_ctrl_dev(magnet):
    if magnet['area'] in ('BSYH', 'BSYS'):
        return 'MGNT:BSY0:1'
    if magnet['area'] in ('CLTH', 'CLTS'):
        return 'MGNT:BSY0:1:CU'
    if magnet['area'] in ('SLTH', 'SLTS'):
        return 'MGNT:BSY0:1:SC'
    if magnet['device'].startswith('EFC:'):
        return 'MGNT:{}:2'.format(magnet['area'])

    return 'MGNT:{}:1'.format(magnet['area'])


def get_magnets_by_wild_ctrl_dev(wild_ctrl_dev):
    return [magnet for magnet in itervalues(magnets) if
            get_wild_ctrl_dev(magnet) == wild_ctrl_dev and not is_string(magnet)]


def get_magnets_by(key, value, wildcard=False):
    if wildcard:
        return [magnet for magnet in itervalues(magnets) if fnmatch.fnmatch(magnet[key], value)]

    return [magnet for magnet in itervalues(magnets) if magnet[key] == value]


def get_magnets_by_multiple(key, values, wildcard=False):
    if wildcard:
        return [magnet for magnet in itervalues(magnets) if
                any(fnmatch.fnmatch(magnet[key], value) for value in values)]

    return [magnet for magnet in itervalues(magnets) if magnet[key] in values]


def warn_about_writes_if_enabled():
    global warned_about_writes, enable_writes
    if enable_writes and not warned_about_writes:
        warned_about_writes = True
        response = input('Are you want to write to production PVs (yes/NO)? ')
        if response != 'yes':
            enable_writes = False


def round_dec_places(x, desired_places):
    if x is None or isnan(x):
        return float('nan')

    if x == 0:
        return 0

    expon = int(floor(log10(abs(x))))
    places = desired_places - expon
    prec = Decimal(10) ** -places

    # Utilize decimal library to prevent floating-point rounding error
    rounded = Decimal(str(x)).quantize(prec, rounding=ROUND_HALF_UP)
    return float(rounded)


def almost_equal(x, y, desired_places=6):
    x_rounded = round_dec_places(to_float(x), desired_places)
    y_rounded = round_dec_places(to_float(y), desired_places)
    return x_rounded == y_rounded


def get_user():
    return os.environ.get('SOFTEGR_USER', getpass.getuser())


def array_almost_equal(xx, yy, desired_places=6):
    return all(almost_equal(x, y, desired_places) for x, y in zip(xx, yy))


def is_string(magnet):
    # Returns True if PS Config is String or (SW PS String is not blank and is different from Element)
    return magnet['ps_config'] == 'String' or (magnet.get('sw_ps_string') and magnet.get('sw_ps_string') != magnet[
        'element'])
