"""
This class implements a class for parsing traceroute output.
"""

import re
from compat import text_type
import sys

class Probe(object):
    """
    This represents a traceroute probe. A probe is one attempt to get info from one hop.
    """
    def __init__(self, rtt, dest, dest_ip):

        self.dest = None
        self.rtt = None
        self.dest_ip = None

        # Process the RTT
        if rtt is not None and len(rtt) > 0 and rtt[0] == '<':
            self.rtt = int(rtt[1:])
        elif rtt == '*' or rtt is None:
            self.rtt = None
        elif len(rtt) > 0:
            self.rtt = float(rtt)

        # Process the dest
        if dest == 'Request timed out.':
            self.dest = None
        elif dest is not None:
            self.dest = dest.strip()

        # Process the dest_ip
        if dest_ip == 'Request timed out.':
            self.dest_ip = None
        elif dest_ip is not None:
            self.dest_ip = dest_ip.strip()

class Hop(object):
    """
    This represents a single hop between a host and its destination.
    A hop can contain multiple probes (since a single hop may be tested more than once).
    """
    def __init__(self, number=None):
        self.number = number
        self.probes = []

    def add_probe(self, probe):
        """
        Add a probe to this hop.
        """

        if probe is not None:

            # Populate the dest from the previous probe if it doesn't have it defined
            if probe.dest is None and len(self.probes) > 0:
                probe.dest = self.probes[-1].dest

            # Populate the dest_ip from the previous probe if it doesn't have it defined
            if probe.dest_ip is None and len(self.probes) > 0:
                probe.dest_ip = self.probes[-1].dest_ip

            # Add the probe
            self.probes.append(probe)

class UnexpectedInputException(Exception):
    """
    This exception is generated when input was observed that is unexpected.
    """

    pass

class Traceroute(object):
    """
    This class will parse traceroutes done using the command-line tools like "traceroute" and
    "tracert".
    """

    # Regexs for things to disregard
    TRACE_COMPLETE = re.compile(r'^\s*Trace complete')