from typing import Optional

import printerconstants


def center(
    text,                   # type: str
    cols=printerconstants.COLS     # type: Optional[int]
):
    # type: (...) -> str

    if not text:
        return text
    text = cut(text)
    miss = cols - len(text)
    if miss == 0:
        return text
    left = miss / 2
    return (" " * left) + text


def center_text(
    text,                       # type: str
    sep=" ",                    # type: str
    line_size=printerconstants.COLS    # type: Optional[int]
):
    # type: (...) -> str

    text = " %s " % text
    begin = sep * int((line_size - len(text)) / 2)
    middle = begin + text
    end = sep * (line_size - len(middle))

    return middle + end


def cut(
    s   # type: str
):
    # type: (...) -> str

    if len(s) > printerconstants.COLS:
        # If there is a line-feed at the end, keep it
        return s[:printerconstants.COLS] if (s[-1] != "\n") else (s[:(printerconstants.COLS - 1)] + "\n")
    return s


def get_text_ellipsis(
    text_id,        # type: str
    text,           # type: str
    padding_space   # type: int
):
    # type: (...) -> str

    remaining_space = printerconstants.COLS - (len(text_id) + padding_space)
    return "{}...".format(text[:remaining_space - 3]) if len(text) > remaining_space else "{}".format(text)
