import re

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'

    def __init__(self):
        super(TSScreenIOCsTest, self).__init__(
            pre_checkout_routines=[]
        )
        self.screeniocs_path = '$EPICS_IOCS/screeniocs'
        self.pattern_template = r'^{}\s+{}\s+{}\s+\S+\s*(?:#.*)?$'

    def execute(self, magnet):
        if magnet['psc_type'] != 'EMCOR':
            self.status = None
            return

        psc_node = 'cpu-{}-mg{}'.format(magnet['loca'].lower(), magnet['crate_num'].zfill(2))
        ioc_pattern = self.pattern_template.format(re.escape(psc_node), re.escape(magnet['ts_node']),
                                                   re.escape(str(magnet['ts_port'])))
        ioc_pattern_re = re.compile(ioc_pattern)
        agent = FacilityAgent(utilities.facility)
        screeniocs_content = agent.read_file(self.screeniocs_path)
        for line in screeniocs_content.splitlines():
            if ioc_pattern_re.match(line):
                self.data = line
                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'
