# This file is part of LocalStack.
# It is adapted from aws-xray-sdk-python licensed under the Apache License 2.0.
# You may obtain a copy of the Apache License 2.0 at http://www.apache.org/licenses/LICENSE-2.0
# Original source: https://github.com/aws/aws-xray-sdk-python/blob/master/aws_xray_sdk/core/models/traceid.py

import binascii
import os
import time


class TraceId:
    """
    A trace ID tracks the path of a request through your application.
    A trace collects all the segments generated by a single request.
    A trace ID is required for a segment.
    """

    VERSION = "1"
    DELIMITER = "-"

    def __init__(self):
        """
        Generate a random trace id.
        """
        self.start_time = int(time.time())
        self.__number = binascii.b2a_hex(os.urandom(12)).decode("utf-8")

    def to_id(self):
        """
        Convert TraceId object to a string.
        """
        return "{}{}{}{}{}".format(
            TraceId.VERSION,
            TraceId.DELIMITER,
            format(self.start_time, "x"),
            TraceId.DELIMITER,
            self.__number,
        )
