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 StandardizeTest(AutoCheckoutTest):
    test_id = 'standardize'
    description = 'Standardize'
    read_only = False
    deferred = False

    def __init__(self):
        super(StandardizeTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        # Ensure standardize is enabled
        if not utilities.results['stdz_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

        # Check that ICTRL and IACT exist and monitor
        fields = ['ICTRL', 'IACT']
        pvs = ['{}:{}'.format(magnet['device'], field) for field in fields]
        for pv in pvs:
            value = epics.caget(pv)
            if value is None:
                self.data = '{} not found'.format(pv)
                self.status = False
                print 'FAIL'
                return

            epics.camonitor(pv, callback=self.record_data)

        # Begin standardization
        ctrl_pv = '{}:CTRL'.format(magnet['device'])
        agent = FacilityAgent(utilities.facility)
        try:
            agent.caput(ctrl_pv, 'STDZ')
        except (subprocess.CalledProcessError, CAException) as e:
            for pv in pvs:
                epics.camonitor_clear(pv)

            self.data = 'Error trying to standardize {}: {}'.format(magnet['device'], e.output)
            self.status = False
            print 'FAIL'
            return

        # Wait until standardization is done
        ctrl_state_pv = magnet['device'] + ':CTRLSTATE'
        ctrl_state = epics.caget(ctrl_state_pv, as_string=True)
        while ctrl_state != 'Done':
            if ctrl_pv is None:
                for pv in pvs:
                    epics.camonitor_clear(pv)

                self.data = '{} not found'.format(ctrl_state_pv)
                self.status = False
                print 'FAIL'

            print 'Not done standardizing 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 standardization was successful
        stdz_ok_pv = '{}:STDZOK'.format(magnet['device'])
        stdz_ok = epics.caget(stdz_ok_pv)
        if stdz_ok is None:
            self.data = '{} not found'.format(stdz_ok_pv)
            self.status = False
            print 'FAIL'
            return

        if not stdz_ok:
            snl_stat_msg_pv = '{}:SNLSTATMSG'.format(magnet['device'])
            snl_stat_msg = epics.caget(snl_stat_msg_pv)
            self.data = 'Standardize failed: {}'.format(snl_stat_msg)
            self.status = False
            print 'FAIL'
            return

        detail_lines = ['Standardize successful']

        # Save standardization time
        stdz_tod_pv = '{}:STDZTOD'.format(magnet['device'])
        stdz_tod = epics.caget(stdz_tod_pv)
        if stdz_tod is None:
            self.data = '{} not found'.format(stdz_tod_pv)
            self.status = False
            print 'FAIL'
            return

        detail_lines.append('{} = {}'.format(stdz_tod_pv, stdz_tod))
        self.data = '\n'.join(detail_lines)
        self.status = True
        print 'PASS'
