import subprocess

from helpers import mgnt_utilities as utilities
from helpers.mgnt_facility_agent import FacilityAgent, CAException
from mgnt_auto_checkout_test import AutoCheckoutTest


class ACSWPowerTest(AutoCheckoutTest):
    test_id = 'acsw_power'
    description = 'ACSW power control'

    def __init__(self):
        super(ACSWPowerTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        if not magnet['acsw_node']:
            self.status = None
            return

        # Power off ACSW plug
        power_off_pv = '{}:{}POWEROFF'.format(magnet['acsw_name'], magnet['acsw_plug'])
        agent = FacilityAgent(utilities.facility)
        try:
            agent.caput(power_off_pv, 1)
        except (subprocess.CalledProcessError, CAException) as e:
            self.data = 'Error trying to power off {}: {}'.format(magnet['acsw_node'], e.output)
            self.status = False
            print 'FAIL'
            return

        # Ping SIOC to ensure it goes away
        ioc_node = magnet['ioc'].lower().replace('sioc', 'cpu').replace(':', '-')
        try:
            agent.ping(ioc_node)
            self.data = '{} was powered off but {} is still online'.format(magnet['acsw_node'], ioc_node)
            self.status = False
            print 'FAIL'
            return

        except subprocess.CalledProcessError:
            pass

        # Power on ACSW plug
        power_on_pv = '{}:{}POWERON'.format(magnet['acsw_name'], magnet['acsw_plug'])
        try:
            agent.caput(power_on_pv, 1)
        except (subprocess.CalledProcessError, CAException) as e:
            self.data = 'Error trying to power on {}: {}'.format(magnet['acsw_node'], e.output)
            self.status = False
            print 'FAIL'
            return

        # Wait?
        # Ping SIOC to ensure it comes back
        try:
            agent.ping(ioc_node)
            self.status = True
            print 'PASS'

        except subprocess.CalledProcessError:
            self.data = '{} was powered back on but {} is offline'.format(magnet['acsw_node'], ioc_node)
            self.status = False
            print 'FAIL'
