import epics.ca

from mgnt_auto_checkout_test import AutoCheckoutTest


class InServiceTest(AutoCheckoutTest):
    test_id = 'in_service'
    description = 'In service'

    def __init__(self):
        super(InServiceTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        # Check if in service
        out_of_service_pv = '{}:OUTOFSERVICE'.format(magnet['device'])
        out_of_service = epics.caget(out_of_service_pv, as_string=True)
        if out_of_service is None:
            self.data = '{} not found'.format(out_of_service_pv)
            self.status = False
            print 'FAIL'
            return

        if out_of_service == 'Out-of-Service':
            # Make sure that status is offline
            stat_msg_pv = '{}:STATMSG'.format(magnet['device'])
            stat_msg = epics.caget(stat_msg_pv, as_string=True)
            if stat_msg == 'Offline':
                self.data = '{}, {}'.format(out_of_service, stat_msg)
                self.status = True
                print 'PASS'

            elif stat_msg is not None:
                self.data = '{} is {} but {} is {} instead of Offline'.format(magnet['device'], out_of_service,
                                                                              stat_msg_pv, stat_msg)
                self.status = False
                print 'FAIL'

            else:
                self.data = '{} not found'.format(stat_msg_pv)
                self.status = False
                print 'FAIL'

        else:
            self.data = out_of_service
            self.status = True
            print 'PASS'
