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 = False
    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):
        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'
