from __future__ import print_function

from helpers import mgnt_utilities as utilities
from helpers.mgnt_facility_agent import FacilityAgent
from .mgnt_auto_checkout_test import AutoCheckoutTest


class TSScreenIOCsTest(AutoCheckoutTest):
    test_id = 'ts_screeniocs'
    description = 'Terminal server in screeniocs'
    read_only = True
    deferred = False

    def __init__(self):
        super(TSScreenIOCsTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Ensure that a terminal server is configured correctly in `screeniocs`.

        1. N/A if magnet is not EMCOR-controlled.
        1. Determine the IOC node by taking the IOC name, replacing colons with hyphens, and lowercasing.
        2. Read `$EPICS_IOCS/screeniocs`.
        3. Ensure that the IOC node appears in the following format:
           <IOC node>    <TS node>    <TS port>

        4. If that line is missing from `screeniocs`, FAIL, otherwise PASS.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        if magnet['psc_type'] != 'EMCOR':
            self.status = None
            return

        psc_node = 'cpu-{}-mg{}'.format(magnet['loca'].lower(), magnet['crate_num'].zfill(2))
        agent = FacilityAgent(utilities.facility)
        screeniocs_entry = agent.get_screeniocs_entry(psc_node)
        if screeniocs_entry:
            self.data = screeniocs_entry
            self.status = True
            print('PASS')
            return

        self.data = "Line containing ``{} {} {}'' not found in screeniocs".format(psc_node, magnet['ts_node'],
                                                                                  magnet['ts_port'])
        self.status = False
        print('FAIL')
