#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributors.

from fenrirscreenreader.core import debug


def get_text_between_marks(firstMark, secondMark, in_text):
    if in_text is None:
        return ""
    if not isinstance(in_text, list):
        in_text = in_text.split("\n")
    if len(in_text) < 1:
        return ""
    if firstMark is None:
        return ""
    if secondMark is None:
        return ""
    if (firstMark["y"] + 1) * (firstMark["x"] + 1) <= (secondMark["y"] + 1) * (
        secondMark["x"] + 1
    ):
        start_mark = firstMark.copy()
        end_mark = secondMark.copy()
    else:
        end_mark = firstMark.copy()
        start_mark = secondMark.copy()
    text_part = ""
    if start_mark["y"] == end_mark["y"]:
        text_part += in_text[start_mark["y"]][
            start_mark["x"] : end_mark["x"] + 1
        ]
    else:
        curr_y = start_mark["y"]
        while curr_y <= end_mark["y"]:
            if curr_y < end_mark["y"]:
                if curr_y == start_mark["y"]:
                    text_part += in_text[curr_y][start_mark["x"] :]
                else:
                    text_part += in_text[curr_y]
                if len(in_text[curr_y].strip()) != 0:
                    if len(text_part) - len(text_part.rstrip()) > 0:
                        text_part = text_part[: len(text_part.rstrip())] + "\n"
                else:
                    text_part += "\n"
            else:
                text_part += in_text[curr_y][: end_mark["x"] + 1]
            curr_y += 1
    return text_part


def get_text_before_mark(mark, in_text):
    if in_text is None:
        return ""
    if mark is None:
        return ""
    return get_text_between_marks({"x": 0, "y": 0}, mark, in_text)


def get_text_after_mark(mark, in_text):
    if in_text is None:
        return ""
    if mark is None:
        return ""
    in_text = in_text.split("\n")
    return get_text_between_marks(
        mark, {"x": len(in_text[0]) - 1, "y": len(in_text) - 1}, in_text
    )
