from __future__ import print_function

from tests.mgnt_get_archived_pvs import GetArchivedPVs
from .mgnt_auto_checkout_test import AutoCheckoutTest


class ArchivedPVsTest(AutoCheckoutTest):
    test_id = 'archived_pvs'
    description = 'PVs archived'
    read_only = True
    deferred = False

    def __init__(self):
        super(ArchivedPVsTest, self).__init__(
            pre_checkout_routines=[GetArchivedPVs]
        )

    def execute(self, magnet):
        """Ensures that a magnet's model and B-field PVs are being archived.

        1. Get all archived PVs.
        2. Check if `<device name>:{BDES, BACT, BCON, EDES, EACT, ECON}` are all being archived.
        3. PASS if all PVs are in the list, otherwise FAIL and print the PVs that are missing.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        pv_set = GetArchivedPVs().data
        fields = ['BDES', 'BACT', 'BCON', 'EDES', 'EACT', 'ECON']
        pvs = ['{}:{}'.format(magnet['device'], field) for field in fields]
        missing_fields = [field for field, pv in zip(fields, pvs) if pv not in pv_set]
        if missing_fields:
            self.data = '{} not archived'.format(', '.join(missing_fields))
            self.status = False
            print('FAIL')

        else:
            self.data = '{} all archived'.format(', '.join(fields))
            self.status = True
            print('PASS')
