from __future__ import print_function

import os.path
import re

from helpers import mgnt_utilities as utilities
from helpers.mgnt_facility_agent import FacilityAgent
from .mgnt_auto_checkout_test import AutoCheckoutTest


class BumplessRebootTest(AutoCheckoutTest):
    test_id = 'bumpless_reboot'
    description = 'Bumpless reboot'
    read_only = True
    deferred = False

    def __init__(self):
        super(BumplessRebootTest, self).__init__(
            pre_checkout_routines=[]
        )
        self.ioc_data_dir = '$IOC_DATA'
        self.pattern_template = r'^{}\b'

    def execute(self, magnet):
        """Ensures that PVs for a magnet are restored on reboot.

        1. Determine the .sav filename by taking the IOC name, replacing colons with hyphens, and appending `.sav`.
        2. Check that the save file exists in `$IOC_DATA`.
        3. Search for the device name in the save file.
        4. FAIL if save file does not exist or device name is not found in it, otherwise PASS.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        ioc_node = magnet['ioc'].lower().replace(':', '-')
        save_file = magnet['ioc'].replace(':', '-') + '.sav'
        save_file_path = os.path.join(self.ioc_data_dir, ioc_node, 'restore', save_file)
        agent = FacilityAgent(utilities.facility)
        if not agent.is_file(save_file_path):
            self.data = '{} not found'.format(save_file_path)
            self.status = False
            print('FAIL')
            return

        restore_pattern = self.pattern_template.format(magnet['device'])
        restore_pattern_re = re.compile(restore_pattern)
        save_file_contents = agent.read_file(save_file_path)
        for line in save_file_contents.splitlines():
            if restore_pattern_re.match(line):
                self.data = '{} found in {}'.format(magnet['device'], save_file_path)
                self.status = True
                print('PASS')
                return

        self.data = '{} not found in {}'.format(magnet['device'], save_file_path)
        self.status = False
        print('FAIL')
