from __future__ import print_function

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 helpers.mgnt_utilities import is_string
from .mgnt_auto_checkout_test import AutoCheckoutTest


class TrimTest(AutoCheckoutTest):
    test_id = 'trim'
    description = 'Trim'
    read_only = False
    deferred = False

    def __init__(self):
        super(TrimTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Performs trim test.

        1. N/A if magnet is not in service.
        2. N/A if magnet has trim disabled.
        3. N/A if magnet is string or bulk.
        4. Attempt to turn on magnet by running `caput <magnet>:STATESETPT 1`.
        5. FAIL if `caput` times out.
        6. Wait 2 seconds
        7. Attempt to `caget <magnet>:STATE`.
        8. FAIL if `caget` times out.
        9. FAIL if `<magnet>:STATE` is `OFF`.
        10. Attempt to `caget <magnet>:STATMSG`.
        11. FAIL if `caget` times out.
        12. If `STATMSG` is `Not Degaus'd`, then degauss magnet.
        13. If `STATMSG` is `Not Stdz'd`, then standardize magnet.
        14. Attempt to save BDES by running `caput <magnet>:CTRL SAVE_BDES`.
        15. FAIL if `caput` times out.
        16. Start monitoring BDES, BACT, IACT, and ICTRL.
        17. Set BDES to three values between BMIN and BMAX:
            a. Attempt to `caput <magnet>:BDES <value>`.
            b. Stop monitoring and FAIL if `caput` times out.
            c. Attempt to perturb magnet by running `caput <magnet>:CTRL TRIM`.
            d. FAIL if `caput` times out.
            e. Wait until `<magnet>:CTRLSTATE` is `Done`.
            f. Attempt to `caget <magnet>:TRIMOK`.
            g. FAIL if `caget` times out.
            h. If `TRIMOK` is `0`, wait 1 second and check `SNLSTATMSG`.
            i. If `SNLSTATMSG` is not `already within tolerance`, then FAIL.
            j. Attempt to `caget <magnet>:TRIMTIME`.
            k. FAIL if `caget` times out.
            l. If `TRIMTIME` is nonzero, FAIL.
        16. Stop monitoring BDES, BACT, IACT, and ICTRL.
        17. Attempt to load BDES by running `caput <magnet>:CTRL LOAD_BDES`.
        18. FAIL if `caput` times out.
        19. Attempt to trim magnet by running `caput <magnet>:CTRL TRIM`.
        20. FAIL if `caput` times out.
        21. Wait until `<magnet>:CTRLSTATE` is `Done` and PASS.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        # Ensure device is in service
        if utilities.results['in_service'].data != 'In-Service':
            self.status = None
            return

        # Ensure trim is enabled
        if not utilities.results['trim_enabled'].data.startswith('Enabled'):
            self.status = None
            return

        # Ensure that magnet is not a string or bulk
        if is_string(magnet) or magnet['psc_type'] == 'SERIAL':
            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.decode('utf-8'))
            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

        # Degauss and/or standardize first if needed
        stat_msg_pv = '{}:STATMSG'.format(magnet['device'])
        stat_msg = epics.caget(stat_msg_pv, as_string=True)
        if stat_msg is None:
            self.data = '{} not found'.format(stat_msg_pv)
            self.status = False
            print('FAIL')
            return

        if stat_msg == "Not Degaus'd":
            print('Degaussing first...')

            # Begin degauss
            ctrl_pv = '{}:CTRL'.format(magnet['device'])
            agent = FacilityAgent(utilities.facility)
            try:
                agent.caput(ctrl_pv, 'DEGAUSS')
            except (subprocess.CalledProcessError, CAException) as e:
                self.data = 'Error trying to degauss {}: {}'.format(magnet['device'], e.output.decode('utf-8'))
                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)

        if stat_msg == "Not Stdz'd":
            print('Standardizing first...')

            # Begin standardization
            ctrl_pv = '{}:CTRL'.format(magnet['device'])
            agent = FacilityAgent(utilities.facility)
            try:
                agent.caput(ctrl_pv, 'STDZ')
            except (subprocess.CalledProcessError, CAException) as e:
                self.data = 'Error trying to standardize {}: {}'.format(magnet['device'], e.output.decode('utf-8'))
                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':
                print('Not done standardizing yet, waiting...')
                time.sleep(1)
                ctrl_state = epics.caget(ctrl_state_pv, as_string=True)

        # Save BDES
        ctrl_pv = '{}:CTRL'.format(magnet['device'])
        agent = FacilityAgent(utilities.facility)
        try:
            agent.caput(ctrl_pv, 'SAVE_BDES')
        except (subprocess.CalledProcessError, CAException) as e:
            self.data = 'Error trying to save BDES for {}: {}'.format(magnet['device'], e.output.decode('utf-8'))
            self.status = False
            print('FAIL')
            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'])
        brange = magnet['bmax'] - magnet['bmin']
        margin = 0.0003
        new_bdes_values = np.linspace(magnet['bmin'] + margin * brange, magnet['bmax'] - margin * brange, 3)
        agent = FacilityAgent(utilities.facility)
        detail_lines = []
        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)

                detail_lines.append('Error trying to set {} to {}: {}'.format(bdes_pv, new_bdes, e.output.decode('utf-8')))
                self.status = False
                print('FAIL')
                continue

            # Trim
            ctrl_pv = '{}:CTRL'.format(magnet['device'])
            try:
                agent.caput(ctrl_pv, 'TRIM')
            except (subprocess.CalledProcessError, CAException) as e:
                for pv in pvs:
                    epics.camonitor_clear(pv)

                detail_lines.append('Error trying to trim {}: {}'.format(magnet['device'], e.output.decode('utf-8')))
                self.status = False
                print('FAIL')
                continue

            # Wait 1 second for trim to start
            time.sleep(1)

            # Wait until trim 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 trimming yet, waiting...')
                time.sleep(1)
                ctrl_state = epics.caget(ctrl_state_pv, as_string=True)

            if self.data:
                print('FAIL')
                continue

            # Check if trim was successful
            trim_ok_pv = '{}:TRIMOK'.format(magnet['device'])
            trim_ok = epics.caget(trim_ok_pv)
            already_within_tol = False
            if trim_ok is None:
                detail_lines.append('{} not found'.format(trim_ok_pv))
                self.status = False
                print('FAIL')
                continue

            if not trim_ok:
                # Wait 1 second for status message to update
                time.sleep(1)
                snl_stat_msg_pv = '{}:SNLSTATMSG'.format(magnet['device'])
                snl_stat_msg = epics.caget(snl_stat_msg_pv)

                # OK if already within tolerance
                if 'already within tolerance' not in snl_stat_msg:
                    detail_lines.append('Trimming to {} failed: {}'.format(new_bdes, snl_stat_msg))
                    self.status = False
                    print('FAIL')
                    continue

                already_within_tol = True

            # Make sure trim time is nonzero
            trim_time_pv = magnet['device'] + ':TRIMTIME'
            trim_time = epics.caget(trim_time_pv)
            if trim_time is None:
                detail_lines.append('{} not found'.format(trim_time_pv))
                self.status = False
                print('FAIL')
                continue

            if trim_time == 0 and not already_within_tol:
                detail_lines.append('Finished trimming to {} but {} is {}'.format(new_bdes, trim_time_pv, trim_time))
                self.status = False
                print('FAIL')
                continue

        # Stop monitoring BDES, BACT, IACT, and ICTRL
        for pv in pvs:
            epics.camonitor_clear(pv)

        # Load BDES
        try:
            agent.caput(ctrl_pv, 'LOAD_BDES')
        except (subprocess.CalledProcessError, CAException) as e:
            detail_lines.append('Error trying to load BDES for {}: {}'.format(magnet['device'], e.output.decode('utf-8')))
            self.status = False
            print('FAIL')

        # Trim
        ctrl_pv = '{}:CTRL'.format(magnet['device'])
        try:
            agent.caput(ctrl_pv, 'TRIM')
        except (subprocess.CalledProcessError, CAException) as e:
            for pv in pvs:
                epics.camonitor_clear(pv)

            detail_lines.append('Error trying to trim {}: {}'.format(magnet['device'], e.output.decode('utf-8')))
            self.status = False
            print('FAIL')

        # Wait until trim 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 trimming yet, waiting...')
            time.sleep(1)
            ctrl_state = epics.caget(ctrl_state_pv, as_string=True)

        # Do nothing else on failure
        if self.status is not False:
            detail_lines.append('Successfully trimmed {} to {}'.format(bdes_pv, new_bdes_values))
            self.status = True
            print('PASS')

        # Put together details
        self.data = '\n'.join(detail_lines)
