#!/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)
#     14-Dec-2022, A. Le (anle)
#         Add ability to trim different kinds of blanks
#     08-Dec-2022, A. Le (anle)
#         Reformat code
#         Add docstrings
#     17-Jun-2022, A. Le (anle)
#         Trim nones instead of zeros
#     31-May-2022, A. Le (anle)
#         Make code compatible with Python 2 and 3
#     01-Oct-2021, A. Le (anle)
#         Prevent floating-point rounding error
#     23-Aug-2021, 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
#
# ==============================================================
#
from __future__ import print_function

from decimal import ROUND_HALF_UP, Decimal
from math import floor, log10


def trim_blanks(coeff):
    """Removes falsy values from the end of a list of polynomial coefficients.

    In this context, `0`s and `Nones` are removed from the right side of the polynomial (higher order terms).

    Args:
        coeff (tuple[float | None, ...]): The polynomial coefficients.

    Returns:
        list[float]: The same list of coefficients without falsy values at the end.
    """
    # Start from the end of the list
    right_index = len(coeff) - 1

    # Keep shifting the index leftward until we hit a truthy value in the list
    while right_index >= 0 and not coeff[right_index]:
        right_index -= 1

    # If index goes out of bounds, there are no falsy values, so return the list unchanged
    if right_index == -1:
        return coeff

    # Otherwise, trim off the list starting from the first falsy value
    return coeff[:right_index + 1]


def round_dec_places(x, desired_places):
    """Rounds a number as if it were in scientific notation.

    Examples:
        >>> round_dec_places(3.14159, 3)
        3.142

        >>> round_dec_places(1.23456789e-7, 6)
        1.234568e-07

    Args:
        x (float): The number to be rounded.
        desired_places (int): The number of decimal places to which to round.

    Returns:
        float: The rounded number.
    """
    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)
