from __future__ import print_function

import subprocess

from helpers import mgnt_utilities as utilities
from .mgnt_auto_checkout_test import AutoCheckoutTest


class EthernetPingTest(AutoCheckoutTest):
    test_id = 'ethernet_ping'
    description = 'CPU name'
    read_only = True
    deferred = False

    def __init__(self):
        super(EthernetPingTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Ensures that a magnet's power supply responds when pinged.

        1. N/A if magnet is not EPSC- or EMCOR-controlled.
        2. N/A if magnet is EMCOR-controlled but failed the DHCP test
        3. If magnet is EPSC, form the nodename by lowercasing the PSC device and replacing colons with hyphens
        4. Otherwise, let the nodename be `cpu-<HW area>-mg<zero-padded crate number>`.
        5. Ping nodename once.
        6. FAIL if `ping` fails, otherwise PASS.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        if magnet['psc_type'] not in ('EPSC', 'EMCOR'):
            self.status = None
            return

        if magnet['psc_type'] == 'EPSC':
            psc_node = magnet['psc_device'].lower().replace(':', '-')
        elif not utilities.results['dhcp_conf'].status:
            # EMCOR, but node not found in dhcp
            self.status = None
            return

        else:
            psc_node = 'cpu-{}-mg{}'.format(magnet['loca'].lower(), magnet['crate_num'].zfill(2))

        ping_command = ['ping', '-c', '1', psc_node]
        try:
            subprocess.check_output(ping_command)
            self.data = 'Pinged ' + psc_node
            self.status = True
            print('PASS')

        except subprocess.CalledProcessError as e:
            self.data = e.output.decode('utf-8')
            self.status = False
            print('FAIL')
