from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence, QContextMenuEvent, QTextCursor, QKeyEvent
from PyQt5.QtWidgets import QAction, QPlainTextEdit, QMenu, QInputDialog


class ScreenTextViewer(QPlainTextEdit):

    def __init__(self):
        super().__init__()
        self.setReadOnly(True)
        self.find_text = ""
        self.setFocusPolicy(Qt.StrongFocus)

    def contextMenuEvent(self, e: QContextMenuEvent) -> None:
        menu = QMenu()

        action_find = QAction("&Find", self)
        action_find.setStatusTip("Find text")
        action_find.triggered.connect(self.on_find)
        menu.addAction(action_find)

        menu.exec(e.globalPos())

    def keyPressEvent(self, e: QKeyEvent) -> None:
        if e.key() == Qt.Key_F and e.modifiers() == Qt.ControlModifier:
            self.on_find()
        elif e.key() == Qt.Key_F3:
            text_cursor = self.find(self.find_text)
            if text_cursor:
                self.moveCursor(QTextCursor.WordRight,
                                QTextCursor.KeepAnchor)
        else:
            super().keyPressEvent(e)

    def on_find(self):
        text_to_find, ok = QInputDialog.getText(self,
                                                'Find text',
                                                'Enter the text to find')
        if ok and text_to_find:
            self.find_text = text_to_find
            text_cursor = self.find(text_to_find)

            if text_cursor:
                self.moveCursor(QTextCursor.WordRight,
                                QTextCursor.KeepAnchor)
