from __future__ import print_function

import numpy as np

from helpers.mgnt_utilities import array_almost_equal
from tests.mgnt_get_poly_from_epics import GetPolyFromEPICS
from .mgnt_auto_checkout_test import AutoCheckoutTest
from .mgnt_get_poly_from_oracle import GetPolyFromOracle


class DegausEnabledTest(AutoCheckoutTest):
    test_id = 'degaus_enabled'
    description = 'Degauss enabled'
    read_only = True
    deferred = False

    def __init__(self):
        super(DegausEnabledTest, self).__init__(
            pre_checkout_routines=[GetPolyFromOracle, GetPolyFromEPICS]
        )

    def execute(self, magnet):
        """Ensures that degaus is correctly disabled or enabled for a magnet.

        1. Attempt to `caget <magnet>:DEGAUSENABLE`.
        2. FAIL if `caget` times out.
        3. FAIL if `DEGAUSENABLE` does not match Oracle.
        4. If degauss is enabled:
            a. Attempt to `caget <magnet>:DEGAUSENABLE`, `DEGAUSSETL`, and `DEGAUSWF`.
            b. Make sure that the Oracle and EPICS values match to 6 decimal places (mantissa only).
            c. PASS if values match, otherwise FAIL and print the first mismatch.
        5. Report "Disabled" and PASS.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        # Check if degauss is enabled
        oracle_data = GetPolyFromOracle().data[magnet['element']]
        epics_data = GetPolyFromEPICS().data[magnet['element']]
        degaus_enable_pv = magnet['device'] + ':DEGAUSENABLE'
        degaus_enable_epics = epics_data['DEGAUSENABLE']
        degaus_enable_oracle = oracle_data['degaus_enable']
        if degaus_enable_epics is None:
            self.data = '{} not found'.format(degaus_enable_pv)
            self.status = False
            print('FAIL')

        elif degaus_enable_oracle != degaus_enable_epics:
            self.data = '{} = {} in EPICS but should be {} according to polynomial database'.format(degaus_enable_pv,
                                                                                                    degaus_enable_epics,
                                                                                                    degaus_enable_oracle)
            self.status = False
            print('FAIL')

        elif degaus_enable_epics:
            # Check ramp rate, settle time, and waveform
            fields = ['DEGAUSRAMPRATE', 'DEGAUSSETL', 'DEGAUSWF']
            detail_lines = ['Enabled']
            for field in fields:
                pv = '{}:{}'.format(magnet['device'], field)
                oracle_value = oracle_data[field.lower()]
                epics_value = epics_data[field]
                if isinstance(oracle_value, np.ndarray) and isinstance(epics_value, np.ndarray):
                    same_values = array_almost_equal(oracle_value, epics_value)
                else:
                    same_values = oracle_value == epics_value

                if not same_values:
                    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')

        else:
            self.data = 'Disabled'
            self.status = True
            print('PASS')
