from __future__ import print_function

import subprocess

from .mgnt_auto_checkout_test import AutoCheckoutTest


class TSPingTest(AutoCheckoutTest):
    test_id = 'ts_ping'
    description = 'Terminal server'
    read_only = True
    deferred = False

    def __init__(self):
        super(TSPingTest, self).__init__(
            pre_checkout_routines=[]
        )

    def execute(self, magnet):
        """Ensures that a magnet's TS host is pingable.

        1. Ping the magnet's TS host once using `ping`.
        2. PASS if `ping` succeeds, otherwise FAIL.

        Args:
            magnet (dict): Information about a magnet from Oracle (Elements, Polynomial, Additional Data)

        Returns:
            None

        """
        if not magnet['ts_node']:
            self.status = None
            return

        ping_command = ['ping', '-c', '1', magnet['ts_node']]
        try:
            subprocess.check_output(ping_command)
            self.data = 'Pinged ' + magnet['ts_node']
            self.status = True
            print('PASS')

        except subprocess.CalledProcessError as e:
            self.data = e.output.decode('utf-8')
            self.status = False
            print('FAIL')
