from __future__ import print_function

import epics

from .mgnt_auto_checkout_test import AutoCheckoutTest


class ACSWPlugName(AutoCheckoutTest):
    test_id = 'acsw_plug_name'
    description = 'Plug has correct name'
    read_only = True
    deferred = False

    def __init__(self):
        super(ACSWPlugName, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Ensures that a magnet's ACSW plug is labeled with the CPU's name.

        1. Get the CPU by taking the magnet's SIOC and replacing `sioc` with `cpu` and `:` with `-`.
        2. Check the value of the PV `<acsw name>:<acsw plug>NAME`
        3. PASS if value matches CPU name, FAIL if they don't match or PV isn't found

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        if not magnet['acsw_node']:
            self.status = None
            return

        node_name = magnet['ioc'].lower().replace('sioc', 'cpu').replace(':', '-')
        acsw_plug_name_pv = '{}:{}NAME'.format(magnet['acsw_name'], magnet['acsw_plug'])
        acsw_plug_name = epics.caget(acsw_plug_name_pv)
        if acsw_plug_name is None:
            self.data = '{} not found'.format(acsw_plug_name_pv)
            self.status = False
            print('FAIL')

        elif acsw_plug_name != node_name:
            self.data = '{} is {} instead of {}'.format(acsw_plug_name_pv, acsw_plug_name, node_name)
            self.status = False
            print('FAIL')

        else:
            self.data = acsw_plug_name
            self.status = True
            print('PASS')
