from __future__ import print_function

import epics

from .mgnt_auto_checkout_test import AutoCheckoutTest


class IOCHeartbeatTest(AutoCheckoutTest):
    test_id = 'ioc_heartbeat'
    description = 'IOC heartbeat'
    read_only = True
    deferred = False

    def __init__(self):
        super(IOCHeartbeatTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Ensures that a magnet's IOC is alive.

        1. Attempt to `caget <IOC>:HEARTBEATSUM`.
        2. FAIL if `caget` times out or `HEARTBEATSUM` is not `PRESENT`.
        3. Attempt to `caget <IOC>:STARTTOD`, `APP_DIR1`, and `APP_DIR2`.
        4. FAIL if `caget` times out.
        5. Combine `APP_DIR1` and `APP_DIR2` to form the app directory.
        6. Return `STARTTOD` and the app directory and PASS.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        heartbeat_sum_pv = magnet['ioc'] + ':HEARTBEATSUM'
        heartbeat_sum = epics.caget(heartbeat_sum_pv, as_string=True)
        if heartbeat_sum is None:
            self.data = '{} not found'.format(heartbeat_sum_pv)
            self.status = False
            print('FAIL')
            return

        if heartbeat_sum != 'PRESENT':
            self.data = 'Heartbeat not detected for {}'.format(magnet['ioc'])
            self.status = False
            print('FAIL')
            return

        detail_lines = [heartbeat_sum]
        start_tod_pv = magnet['ioc'] + ':STARTTOD'
        start_tod = epics.caget(start_tod_pv)
        if start_tod is None:
            self.data = '{} not found'.format(start_tod_pv)
            self.status = False
            print('FAIL')
            return

        detail_lines.append('IOC boot time: ' + start_tod)
        app_dir1_pv = magnet['ioc'] + ':APP_DIR1'
        app_dir1 = epics.caget(app_dir1_pv)
        if app_dir1 is None:
            self.data = '{} not found'.format(app_dir1_pv)
            self.status = False
            print('FAIL')
            return

        app_dir2_pv = magnet['ioc'] + ':APP_DIR2'
        app_dir2 = epics.caget(app_dir2_pv)
        if app_dir2 is None:
            self.data = '{} not found'.format(app_dir2_pv)
            self.status = False
            print('FAIL')

        else:
            detail_lines.append('App dir: ' + app_dir1 + app_dir2)
            self.data = '\n'.join(detail_lines)
            self.status = True
            print('PASS')
