from __future__ import print_function

import epics

from .mgnt_auto_checkout_test import AutoCheckoutTest


class MagnetConfigTest(AutoCheckoutTest):
    test_id = 'magnet_config'
    description = 'Magnet configuration'
    read_only = True
    deferred = False

    def __init__(self):
        super(MagnetConfigTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Checks the magnet configuration.

        1. Attempt to `caget <magnet>:CONFIG`.
        2. FAIL if `caget` times out.
        3. FAIL if `CONFIG` does not match Oracle.
        4. If magnet is String:
            a. Attempt to `caget <magnet>:MAIN`.
            b. FAIL if `caget` times out.
            c. FAIL if `MAIN` does not match PS String.
            d. Report values of `CONFIG` and `MAIN` and PASS.
        5. If magnet is not String:
            a. Report value of `CONFIG` and PASS.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        config_pv = magnet['device'] + ':CONFIG'
        config = epics.caget(config_pv, as_string=True)
        if config is None:
            self.data = '{} not found'.format(config_pv)
            self.status = False
            print('FAIL')

        elif config != magnet['ps_config']:
            self.data = '{} is {} instead of {}'.format(config_pv, config, magnet['ps_config'])
            self.status = False
            print('FAIL')

        elif config == 'String':
            main_pv = magnet['device'] + ':MAIN'
            main = epics.caget(main_pv)
            if main is None:
                self.data = '{} not found'.format(main_pv)
                self.status = False
                print('FAIL')

            elif main != magnet['ps_string']:
                self.data = '{} is {} instead of {}'.format(main_pv, main, magnet['ps_string'])
                self.status = False
                print('FAIL')

            else:
                self.data = '{} with main {}'.format(config, main)
                self.status = True
                print('PASS')

        else:
            self.data = config
            self.status = True
            print('PASS')
