from __future__ import print_function

from helpers.mgnt_utilities import almost_equal
from tests.mgnt_get_poly_from_epics import GetPolyFromEPICS
from tests.mgnt_get_poly_from_oracle import GetPolyFromOracle
from .mgnt_auto_checkout_test import AutoCheckoutTest


class CurrentRangeTest(AutoCheckoutTest):
    test_id = 'current_range'
    description = 'Current range'
    read_only = True
    deferred = False

    def __init__(self):
        super(CurrentRangeTest, self).__init__(
            pre_checkout_routines=[GetPolyFromOracle, GetPolyFromEPICS]
        )

    def execute(self, magnet):
        """Ensures that a magnet's B-field range in EPICS matches what's in Oracle.

        1. Get the magnet's IMIN, IMAX from Oracle and EPICS.
        2. For IMIN and IMAX, make sure that the Oracle and EPICS values match to 6 decimal places (mantissa only).
        3. PASS if IMINs and IMAXs match, otherwise FAIL and print the first mismatch.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        oracle_data = GetPolyFromOracle().data[magnet['element']]
        epics_data = GetPolyFromEPICS().data[magnet['element']]
        fields = ['IMIN', 'IMAX']
        detail_lines = []
        for field in fields:
            pv = '{}:{}'.format(magnet['device'], field)
            oracle_value = oracle_data[field.lower()]
            epics_value = epics_data[field]
            if not almost_equal(oracle_value, epics_value):
                self.data = '{} = {} in EPICS but should be {} according to polynomial database'.format(pv, epics_value,
                                                                                                        oracle_value)
                self.status = False
                print('FAIL')
                return

            else:
                detail_lines.append('{} = {}'.format(field, epics_value))

        self.data = '\n'.join(detail_lines)
        self.status = True
        print('PASS')
