"""
Module for formatting utilities for stacktrace
generated by user logging.exception call
"""
import re

from sap.cf_logging.core import constants


def format_stacktrace(stacktrace):
    """
    Removes tab characters
    Truncates stacktrace to maximum size

    :param stacktrace: string representation of a stacktrace
    """
    if not isinstance(stacktrace, str):
        return ''

    stacktrace = re.sub('\t', '  ', stacktrace)

    if len(stacktrace) <= constants.STACKTRACE_MAX_SIZE:
        return stacktrace

    stacktrace_beginning = _stacktrace_beginning(
        stacktrace, constants.STACKTRACE_MAX_SIZE // 3
    )

    stacktrace_end = _stacktrace_end(
        stacktrace, (constants.STACKTRACE_MAX_SIZE // 3) * 2
    )

    new_stacktrace = "-------- STACK TRACE TRUNCATED --------\n" + stacktrace_beginning +\
        "-------- OMITTED --------\n" + stacktrace_end

    return new_stacktrace

def _stacktrace_beginning(stacktrace, size):
    """ Gets the first `size` bytes of the stacktrace """
    if len(stacktrace) <= size:
        return stacktrace

    return stacktrace[:size]

def _stacktrace_end(stacktrace, size):
    """ Gets the last `size` bytes of the stacktrace """
    stacktrace_length = len(stacktrace)
    if stacktrace_length <= size:
        return stacktrace

    return stacktrace[:-(stacktrace_length-size)]
