import subprocess
import time

import epics
import numpy as np

from helpers import mgnt_utilities as utilities
from helpers.mgnt_facility_agent import FacilityAgent, CAException
from mgnt_auto_checkout_test import AutoCheckoutTest


class PerturbTest(AutoCheckoutTest):
    test_id = 'perturb'
    description = 'Perturb'

    def __init__(self):
        super(PerturbTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        # Ensure device is in service
        if utilities.results['in_service'].data != 'In-Service':
            self.status = None
            return

        # Ensure perturb is enabled
        if not utilities.results['perturb_enabled'].data.startswith('Enabled'):
            self.status = None
            return

        # Ensure that magnet is not a string (what about PSCONTROLLER=="Bulk"??)
        if magnet['ps_config'] == 'String':
            self.status = None
            return

        # Monitor BDES, BACT, IACT, and ICTRL
        fields = ['BDES', 'BACT', 'IACT', 'ICTRL']
        pvs = ['{}:{}'.format(magnet['device'], field) for field in fields]
        for pv in pvs:
            epics.camonitor(pv, callback=self.record_data)

        # Set BDES to 3 values between BMIN and BMAX
        bdes_pv = '{}:BDES'.format(magnet['device'])
        new_bdes_values = np.linspace(magnet['bmin'], magnet['bmax'], 3)
        agent = FacilityAgent(utilities.facility)
        for new_bdes in new_bdes_values:
            # Enter value for BDES
            try:
                agent.caput(bdes_pv, new_bdes)
            except (subprocess.CalledProcessError, CAException) as e:
                for pv in pvs:
                    epics.camonitor_clear(pv)

                self.data = 'Error trying to set {} to {}: {}'.format(bdes_pv, new_bdes, e.output)
                self.status = False
                print 'FAIL'
                return

            # Perturb
            ctrl_pv = '{}:CTRL'.format(magnet['device'])
            try:
                agent.caput(ctrl_pv, 'PERTURB')
            except (subprocess.CalledProcessError, CAException) as e:
                for pv in pvs:
                    epics.camonitor_clear(pv)

                self.data = 'Error trying to perturb {}: {}'.format(magnet['device'], e.output)
                self.status = False
                print 'FAIL'
                return

            # Wait until perturb 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 perturbing yet, waiting...'
                time.sleep(1)
                ctrl_state = epics.caget(ctrl_state_pv, as_string=True)

            # Make sure status is not out of tolerance
            stat_msg_pv = magnet['device'] + ':STATMSG'
            stat_msg = epics.caget(stat_msg_pv, as_string=True)
            if stat_msg == 'Out-of-Tol':
                for pv in pvs:
                    epics.camonitor_clear(pv)

                bact_pv = magnet['device'] + ':BACT'
                bact = epics.caget(bact_pv)
                self.data = '{} is {} after perturbing to {} ({})'.format(bact_pv, bact, new_bdes, stat_msg)
                self.status = False
                print 'FAIL'
                return

        # Stop monitoring BDES, BACT, IACT, and ICTRL
        for pv in pvs:
            epics.camonitor_clear(pv)

        # Go back to 0
        try:
            agent.caput(bdes_pv, 0)
        except (subprocess.CalledProcessError, CAException) as e:
            for pv in pvs:
                epics.camonitor_clear(pv)

            self.data = 'Error trying to set {} to 0: {}'.format(bdes_pv, e.output)
            self.status = False
            print 'FAIL'
            return

        # Perturb
        ctrl_pv = '{}:CTRL'.format(magnet['device'])
        try:
            agent.caput(ctrl_pv, 'PERTURB')
        except (subprocess.CalledProcessError, CAException) as e:
            for pv in pvs:
                epics.camonitor_clear(pv)

            self.data = 'Error trying to perturb {}: {}'.format(magnet['device'], e.output)
            self.status = False
            print 'FAIL'
            return

        # Wait until perturb 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 perturbing yet, waiting...'
            time.sleep(1)
            ctrl_state = epics.caget(ctrl_state_pv, as_string=True)

        self.data = 'Successfully perturbed {} to {}'.format(bdes_pv, new_bdes_values)
        self.status = True
        print 'PASS'
