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


from fenrirscreenreader.core.i18n import _
from fenrirscreenreader.utils import mark_utils


class command:
    def __init__(self):
        pass

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

    def shutdown(self):
        pass

    def get_description(self):
        return _("copies marked text to the currently selected clipboard")

    def get_text_from_screen(self, start_mark, end_mark):
        screen_content = self.env["screen"]["new_content_text"]
        screen_lines = screen_content.split("\n")

        start_y = min(start_mark["y"], len(screen_lines) - 1)
        end_y = min(end_mark["y"], len(screen_lines) - 1)

        # If marks are on the same line
        if start_y == end_y:
            line = screen_lines[start_y]
            start_x = min(start_mark["x"], len(line))
            end_x = min(end_mark["x"], len(line)) + 1
            return line[start_x:end_x]

        # Handle multi-line selection
        result = []

        # First line (from start mark to end of line)
        first_line = screen_lines[start_y]
        start_x = min(start_mark["x"], len(first_line))
        result.append(first_line[start_x:].rstrip())

        # Middle lines (complete lines)
        for lineNum in range(start_y + 1, end_y):
            result.append(screen_lines[lineNum].rstrip())

        # Last line (from start to end mark)
        if end_y > start_y:
            last_line = screen_lines[end_y]
            end_x = min(end_mark["x"], len(last_line)) + 1
            result.append(last_line[:end_x].rstrip())

        return "\n".join(result)

    def run(self):
        if not self.env["commandBuffer"]["Marks"]["1"]:
            self.env["runtime"]["OutputManager"].present_text(
                _("One or two marks are needed"), interrupt=True
            )
            return
        if not self.env["commandBuffer"]["Marks"]["2"]:
            self.env["runtime"]["CursorManager"].set_mark()

        # use the last first and the last setted mark as range
        start_mark = self.env["commandBuffer"]["Marks"]["1"].copy()
        end_mark = self.env["commandBuffer"]["Marks"]["2"].copy()

        # Replace mark_utils.get_text_between_marks with our new method
        marked = self.get_text_from_screen(start_mark, end_mark)

        self.env["runtime"]["MemoryManager"].add_value_to_first_index(
            "clipboardHistory", marked
        )
        # reset marks
        self.env["runtime"]["CursorManager"].clear_marks()
        self.env["runtime"]["OutputManager"].present_text(
            marked, sound_icon="CopyToClipboard", interrupt=True
        )

    def set_callback(self, callback):
        pass
