from __future__ import print_function

import epics

from .mgnt_auto_checkout_test import AutoCheckoutTest


class BarcodeTest(AutoCheckoutTest):
    test_id = 'barcode'
    description = 'Barcode'
    read_only = True
    deferred = False

    def __init__(self):
        super(BarcodeTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Ensures that a magnet's barcode in EPICS matches what's in Oracle.

        1. Get the magnet's barcode from Oracle and EPICS.
        2. Make sure that the Oracle and EPICS barcodes match.
        3. PASS if BMINs and BMAXs, otherwise FAIL and print the first mismatch.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        barcode_pv = magnet['device'] + ':BARCODE'
        barcode = epics.caget(barcode_pv)
        if barcode is None:
            self.data = '{} not found'.format(barcode_pv)
            self.status = False
            print('FAIL')

        elif barcode != magnet['barcode']:
            self.data = '{} is {} instead of {}'.format(barcode_pv, barcode, magnet['barcode'])
            self.status = False
            print('FAIL')

        else:
            self.data = barcode
            self.status = True
            print('PASS')
