import epics

from mgnt_auto_checkout_test import AutoCheckoutTest


class MADNameTest(AutoCheckoutTest):
    test_id = 'mad_name'
    description = 'MAD name'

    def __init__(self):
        super(MADNameTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        # 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'

        if mad_name != magnet['element']:
            self.data = '{} is {} instead of {}'.format(mad_name_pv, mad_name, magnet['element'])
            self.status = False
            print 'FAIL'

        # 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'
