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

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

import re
import string

from fenrirscreenreader.core import debug


class TextManager:
    def __init__(self):
        # https://regex101.com/
        self.regExSingle = re.compile(r"(([^\w\s])\2{5,})")
        self.regExDouble = re.compile(r"([^\w\s]{2,}){5,}")

    def initialize(self, environment):
        self.env = environment

    def shutdown(self):
        pass

    def replace_head_lines(self, text):
        # fast len check for bigger typing echo
        if len(text) < 5:
            return text
        # more strong check, to not match if not needed:
        if (
            len(
                text.strip(
                    string.ascii_letters + string.digits + string.whitespace
                )
            )
            < 5
        ):
            return text
        result = ""
        new_text = ""
        last_pos = 0
        for match in self.regExDouble.finditer(text):
            span = match.span()
            new_text += text[last_pos : span[0]]
            number_of_chars = len(text[span[0] : span[1]])
            name = text[span[0] : span[1]][:2]
            if not self.env["runtime"]["PunctuationManager"].is_puctuation(
                name[0]
            ):
                last_pos = span[1]
                continue
            if name[0] == name[1]:
                new_text += (
                    " "
                    + str(number_of_chars)
                    + " "
                    + self.env["runtime"][
                        "PunctuationManager"
                    ].proceed_punctuation(name[0], True)
                    + " "
                )
            else:
                new_text += (
                    " "
                    + self.env["runtime"][
                        "PunctuationManager"
                    ].proceed_punctuation(name[0], True)
                    + " "
                    + str(int(number_of_chars / 2))
                    + " "
                    + self.env["runtime"][
                        "PunctuationManager"
                    ].proceed_punctuation(name[1], True)
                    + " "
                )
            last_pos = span[1]
        if last_pos != 0:
            new_text += " "
        new_text += text[last_pos:]
        last_pos = 0
        for match in self.regExSingle.finditer(new_text):
            span = match.span()
            result += new_text[last_pos : span[0]]
            number_of_chars = len(new_text[span[0] : span[1]])
            name = new_text[span[0] : span[1]][:2]
            if not self.env["runtime"]["PunctuationManager"].is_puctuation(
                name[0]
            ):
                last_pos = span[1]
                continue
            if name[0] == name[1]:
                result += (
                    " "
                    + str(number_of_chars)
                    + " "
                    + self.env["runtime"][
                        "PunctuationManager"
                    ].proceed_punctuation(name[0], True)
                    + " "
                )
            else:
                result += (
                    " "
                    + self.env["runtime"][
                        "PunctuationManager"
                    ].proceed_punctuation(name[0], True)
                    + " "
                    + str(int(number_of_chars / 2))
                    + " "
                    + self.env["runtime"][
                        "PunctuationManager"
                    ].proceed_punctuation(name[1], True)
                    + " "
                )
            last_pos = span[1]
        if last_pos != 0:
            result += " "
        result += new_text[last_pos:]
        return result
