from __future__ import print_function

import os

from helpers import mgnt_utilities as utilities
from helpers.mgnt_facility_agent import FacilityAgent
from .mgnt_auto_checkout_test import AutoCheckoutTest


class MagnetDisplayTest(AutoCheckoutTest):
    test_id = 'magnet_display'
    description = 'EDM display'
    read_only = True
    deferred = False

    def __init__(self):
        super(MagnetDisplayTest, self).__init__(
            pre_checkout_routines=[]
        )
        self.mgnt_disp_dir = '$EDM/mgnt'
        self.mgnt_disp_glob = os.path.join(self.mgnt_disp_dir, 'mgnt_*.edl')
        self.pattern_template = r'^controlPv "{}:BDES"$'

    def execute(self, magnet):
        """Ensures that at least one display contains a magnet.

        1. Examine files `$EDM/mgnt/mgnt_*.edl` on the appropriate facility.
        2. Get list of files that contain `controlPv "<device>:BDES"`.
        3. FAIL if list is empty.
        4. Report list and PASS.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        display_pattern = self.pattern_template.format(magnet['device'])
        agent = FacilityAgent(utilities.facility)
        matching_files = agent.get_files_containing_pattern(display_pattern, self.mgnt_disp_glob)

        if matching_files:
            self.data = ', '.join(matching_files)
            self.status = True
            print('PASS')

        else:
            self.data = '{}:BDES not found in {}'.format(magnet['device'], self.mgnt_disp_dir)
            self.status = False
            print('FAIL')
