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):
        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')
