from __future__ import print_function

import epics

from helpers.mgnt_utilities import almost_equal
from .mgnt_auto_checkout_test import AutoCheckoutTest


class ZPositionTest(AutoCheckoutTest):
    test_id = 'z_position'
    description = 'Z position'
    read_only = True
    deferred = False

    def __init__(self):
        super(ZPositionTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Ensures that a magnet's Z position in EPICS matches what is in Oracle.

        1. N/A if magnet is a bulk.
        2. Get the magnet's Z position from Oracle and EPICS.
        3. PASS if Oracle and EPICS Z positions match, otherwise fail.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        if magnet['psc_type'] == 'SERIAL':
            self.status = None
            return

        z_pos_pv = magnet['device'] + ':Z'
        z_pos = epics.caget(z_pos_pv)
        if z_pos is None:
            self.data = '{} not found'.format(z_pos_pv)
            self.status = False
            print('FAIL')

        elif not almost_equal(z_pos, magnet['z_pos']):
            self.data = '{} is {} instead of {}'.format(z_pos_pv, z_pos, magnet['z_pos'])
            self.status = False
            print('FAIL')

        else:
            self.data = str(z_pos)
            self.status = True
            print('PASS')
