from __future__ import print_function

import subprocess
import time

import epics

from helpers import mgnt_utilities as utilities
from helpers.mgnt_facility_agent import FacilityAgent, CAException
from .mgnt_auto_checkout_test import AutoCheckoutTest


class DegaussTest(AutoCheckoutTest):
    test_id = 'degauss'
    description = 'Degauss'
    read_only = False
    deferred = False

    def __init__(self):
        super(DegaussTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Performs calibration test.

        1. N/A if magnet has calibration disabled.
        2. N/A if magnet is not in service.
        3. Attempt to turn on magnet by running `caput <magnet>:STATESETPT 1`.
        4. FAIL if `caput` times out.
        5. Wait 2 seconds
        6. Attempt to `caget <magnet>:STATE`.
        7. FAIL if `caget` times out.
        8. FAIL if `<magnet>:STATE` is `OFF`.
        9. Start monitoring `ICTRL` and `IACT`.
        10. Attempt to deguass magnet by running `caput <magnet>:CTRL DEGAUSS`.
        11. FAIL if `caput` times out.
        12. Poll `<magnet>:CTRLSTATE` every second until it is `Done`.
        13. Attempt to `caget <magnet>:DEGAUSOK`.
        14. FAIL if `caget` times out.
        15. Report value of `SNLSTATMSG` and FAIL if `DEGAUSOK` is `0`.
        16. Attempt to `caget <magnet>:DEGAUSTOD`.
        17. FAIL if `caget` times out.
        18. Report value of `DEGAUSTOD` and PASS.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        # Ensure degauss is enabled
        if not utilities.results['degaus_enabled'].data.startswith('Enabled'):
            self.status = None
            return

        # Ensure device is in service
        if utilities.results['in_service'].data != 'In-Service':
            self.status = None
            return

        # Turn device on
        state_set_pt_pv = '{}:STATESETPT'.format(magnet['device'])
        agent = FacilityAgent(utilities.facility)
        try:
            agent.caput(state_set_pt_pv, 1)
        except (subprocess.CalledProcessError, CAException) as e:
            self.data = 'Error trying to power on {}: {}'.format(magnet['device'], e.output)
            self.status = False
            print('FAIL')
            return

        # Wait 2 seconds
        time.sleep(2)

        # Verify that device is on
        state_pv = '{}:STATE'.format(magnet['device'])
        state = epics.caget(state_pv, as_string=True)
        if state is None:
            self.data = '{} not found'.format(state_pv)
            self.status = False
            print('FAIL')
            return

        elif state != 'ON':
            self.data = '{} is expected to be on but {} is {}'.format(magnet['device'], state_pv, state)
            self.status = False
            print('FAIL')
            return

        # Monitor ICTRL and IACT
        fields = ['ICTRL', 'IACT']
        pvs = ['{}:{}'.format(magnet['device'], field) for field in fields]
        for pv in pvs:
            epics.camonitor(pv, callback=self.record_data)

        # Degauss
        ctrl_pv = '{}:CTRL'.format(magnet['device'])
        agent = FacilityAgent(utilities.facility)
        try:
            agent.caput(ctrl_pv, 'DEGAUSS')
        except (subprocess.CalledProcessError, CAException) as e:
            for pv in pvs:
                epics.camonitor_clear(pv)

            self.data = 'Error trying to degauss {}: {}'.format(magnet['device'], e.output)
            self.status = False
            print('FAIL')
            return

        # Wait until degauss is done
        ctrl_state_pv = magnet['device'] + ':CTRLSTATE'
        ctrl_state = epics.caget(ctrl_state_pv, as_string=True)
        while ctrl_state != 'Done':
            print('Not done degaussing yet, waiting...')
            time.sleep(1)
            ctrl_state = epics.caget(ctrl_state_pv, as_string=True)

        # Stop monitoring ICTRL and IACT
        for pv in pvs:
            epics.camonitor_clear(pv)

        # Check if degauss was successful
        degaus_ok_pv = '{}:DEGAUSOK'.format(magnet['device'])
        degaus_ok = epics.caget(degaus_ok_pv)
        if degaus_ok is None:
            self.data = '{} not found'.format(degaus_ok_pv)
            self.status = False
            print('FAIL')
            return

        if not degaus_ok:
            snl_stat_msg_pv = '{}:SNLSTATMSG'.format(magnet['device'])
            snl_stat_msg = epics.caget(snl_stat_msg_pv)
            self.data = 'Degauss failed: {}'.format(snl_stat_msg)
            self.status = False
            print('FAIL')
            return

        detail_lines = ['Degauss successful']

        # Save degauss time
        degaus_tod_pv = '{}:DEGAUSTOD'.format(magnet['device'])
        degaus_tod = epics.caget(degaus_tod_pv)
        if degaus_tod is None:
            self.data = '{} not found'.format(degaus_tod_pv)
            self.status = False
            print('FAIL')
            return

        detail_lines.append('{} = {}'.format(degaus_tod_pv, degaus_tod))
        self.data = '\n'.join(detail_lines)
        self.status = True
        print('PASS')
