from __future__ import print_function

import epics

from .mgnt_auto_checkout_test import AutoCheckoutTest


class MADNameTest(AutoCheckoutTest):
    test_id = 'mad_name'
    description = 'MAD name'
    read_only = True
    deferred = False

    def __init__(self):
        super(MADNameTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Ensures that a magnet's MAD name in EPICS matches what is in Oracle.

        1. Get the magnet's MAD name from Oracle and EPICS.
        2. PASS if Oracle and EPICS MAD names match, otherwise fail.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        # Check MAD name
        mad_name_pv = magnet['device'] + ':MADNAME'
        mad_name = epics.caget(mad_name_pv)
        if mad_name is None:
            self.data = '{} not found'.format(mad_name_pv)
            self.status = False
            print('FAIL')
            return

        if mad_name != magnet['element']:
            self.data = '{} is {} instead of {}'.format(mad_name_pv, mad_name, magnet['element'])
            self.status = False
            print('FAIL')
            return

        # Also element name from PSC
        #if magnet['psc_type'] in ('EPSC', 'EMCOR'):
        #    if magnet['psc_type'] == 'EPSC':
        #        psc_mad_name_pv = magnet['psc_device'] + ':MAGNETID'
        #    else:
        #        psc_mad_name_pv = magnet['psc_device'] + ':NAME'

        #    psc_mad_name = epics.caget(psc_mad_name_pv)
        #    if psc_mad_name is None:
        #        self.data = '{} not found'.format(psc_mad_name_pv)
        #        self.status = False
        #        print('FAIL')
        #        return

        #    if psc_mad_name != magnet['element']:
        #        self.data = '{} is {} instead of {}'.format(psc_mad_name_pv, psc_mad_name, magnet['element'])
        #        self.status = False
        #        print('FAIL')
        #        return

        self.data = mad_name
        self.status = True
        print('PASS')
