#!/usr/bin/env python
#==============================================================
#
#  Abs:   Utility script for mgnt_poly_compare.py
#
#  Name:  mgnt_get_poly.py
#
#  Facility: SLAC Controls (Development)
#
#  Auth:  08-Jul-2020, A. Le (anle)
#--------------------------------------------------------------
#  Mods: (Latest to oldest)
#     23-Aug-2020, A. Le (anle)
#         Rename to mgnt_get_poly.py
#     31-Aug-2020, A. Le (anle)
#         Add ability for trim_zeros to trim blanks
#         Move round_sig_figs function here
#     09-Jul-2020, A. Le (anle)
#         -List device name and operational status
#         -Group devices by area
#         -Report devices missing by area
#         -Take magnets from Oracle Infrastructure database
#         -Add table of missing magnets
#
#==============================================================
#
import re
import glob
import os
from math import floor, log10

def process(line):
    # Remove all spaces and braces
    cleaned = re.sub(r'\s|{|}', '', line)
    
    # Extract device and polynomial coefficients
    data = cleaned.split(',')
    name = data[0]
    device = data[2]
    coeff = data[3:]

    # Trim off zeros
    return name, device, trim_zeros(coeff)

def trim_zeros(coeff):
    right_index = next((i for i, c in enumerate(reversed(coeff)) if c and float(c) != 0), None)
    if right_index is None:
        return []

    return coeff[:len(coeff) - right_index]

def round_sig_figs(x, sig_figs):
    if x == 0:
        return 0

    expon = int(floor(log10(abs(x))))
    places = sig_figs - expon - 1
    return round(x, places)

def get_elem_and_coeff(filename):
    elements = []
    with open(filename) as f:
        # Search for polynomial header
        match = None
        line = f.readline()
        while match is None and line:
            match = re.search(r'\s*{\s*MAD\s*,\s*BARCODE\s*,\s*DEV\s*,\s*A', line)
            line = f.readline()
    
        # Extract polynomial coefficients
        while line and ('{' in line or '}' not in line):
            if '{' in line and '}' in line:
                name, device, coeff = process(line)
                elements.append((name, device, coeff))
    
            line = f.readline()
    
    return elements

def get_elem_dict(db_files):
    element_dict = {}
    for filename in glob.glob(db_files):
        for name, device, coeff in get_elem_and_coeff(filename):
            element_dict[name] = (device, coeff)
    
    return element_dict

if __name__ == '__main__':
    print get_elem_dict('/afs/slac.stanford.edu/u/ad/anle/2020/Magnet/MAIN_TRUNK/mgntApp/Db/lcls/*/*.substitutions')
