#!/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 BarrierManager:
    def __init__(self):
        self.currIsBarrier = False
        self.prefIsBarrier = False

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

    def shutdown(self):
        pass

    def update_barrier_change(self, is_barrier):
        self.prefIsBarrier = self.currIsBarrier
        self.currIsBarrier = is_barrier

    def reset_barrier_change(self):
        self.currIsBarrier = False
        self.prefIsBarrier = False

    def is_barrier_change(self):
        return self.currIsBarrier != self.prefIsBarrier

    def handle_line_barrier(
        self, text, xCursor, yCursor, output=True, do_interrupt=True
    ):
        is_barrier = False
        try:
            is_barrier, say_line = self.get_barrier_text(
                text, xCursor, yCursor
            )
        except Exception as e:
            return False, ""

        self.update_barrier_change(is_barrier)
        if self.is_barrier_change():
            if output:
                if is_barrier:
                    self.env["runtime"]["OutputManager"].play_sound_icon(
                        sound_icon="BarrierStart", interrupt=do_interrupt
                    )
                else:
                    self.env["runtime"]["OutputManager"].play_sound_icon(
                        sound_icon="BarrierEnd", interrupt=do_interrupt
                    )

        if not is_barrier:
            say_line = ""
        return is_barrier, say_line

    def get_barrier_text(self, text, xCursor, yCursor):
        line = text[yCursor]
        if not self.env["runtime"]["SettingsManager"].get_setting_as_bool(
            "barrier", "enabled"
        ):
            return False, line
        offset = xCursor

        left_barriers = self.env["runtime"]["SettingsManager"].get_setting(
            "barrier", "left_barriers"
        )
        right_barriers = self.env["runtime"]["SettingsManager"].get_setting(
            "barrier", "right_barriers"
        )
        # is the cursor at the begin or end of an entry:
        # print(line[:offset + 1].count('│'),line[offset:].count('│'))
        # start

        for b in left_barriers:
            if line[: offset + 1].count(b) > line[offset:].count(b):
                offset = xCursor - 1
            start = line[:offset].rfind(b)
            if start != -1:
                start += 1
                break
        if start == -1:
            return False, line
        # end
        for b in right_barriers:
            end = line[start:].find(b)
            if end != -1:
                end = start + end
                break
        if end == -1:
            return False, line
        if start == end:
            return False, line

        return True, line[start:end]
