from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLineEdit, QTextEdit, QPushButton
from PyQt5.QtGui import QTextCursor, QTextBlockFormat, QTextCharFormat, QColor
from database import add_log_to_db, get_logs_from_db
from datetime import datetime

class LogWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.load_logs_from_db()

    def setup_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)

        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        layout.addWidget(self.log_text)

        self.log_input = QLineEdit()
        self.log_input.setPlaceholderText("Enter log message")
        layout.addWidget(self.log_input)

        buttons_layout = QHBoxLayout()
        log_button = QPushButton("Add Log")
        log_button.clicked.connect(self.add_uilog)
        buttons_layout.addWidget(log_button)
        clear_button = QPushButton("Clear Log")
        clear_button.clicked.connect(self.clear_log)
        buttons_layout.addWidget(clear_button)
        
        buttons_widget = QWidget()
        buttons_widget.setLayout(buttons_layout)
        layout.addWidget(buttons_widget)

    def get_line_count(self):
        document = self.log_text.document()
        return document.blockCount()

    def delete_first_line(self):
        cursor = self.log_text.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor)
        cursor.removeSelectedText()
        self.log_text.setTextCursor(cursor)

    def delete_lines(self, n):
        cursor = self.log_text.textCursor()
        cursor.movePosition(QTextCursor.Start)
        
        for _ in range(n):
            if cursor.atEnd():
                break
            cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor)
            cursor.removeSelectedText()
        
        self.log_text.setTextCursor(cursor)

    def clear_log(self):
        self.log_text.clear()

    def update_log(self, message, foreground=QColor("black"), background=QColor("white")):
        char_format = QTextCharFormat()
        char_format.setForeground(foreground)
        char_format.setBackground(background)

        block_format = QTextBlockFormat()
        block_format.setBackground(background)

        self.log_text.moveCursor(QTextCursor.End)
        cursor = self.log_text.textCursor()
        cursor.insertBlock(block_format)
        cursor.insertText(message, char_format)
        self.log_text.setTextCursor(cursor)

    def add_log(self, message, foreground=QColor("black"), background=QColor("white")):
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        log_message = f"[{timestamp}] {message}"
        self.update_log(log_message, foreground, background)
        add_log_to_db(message)
        self.log_input.clear()
        if 3000 < self.get_line_count():
            self.delete_first_line()

    def add_uilog(self):
        message = self.log_input.text()
        self.add_log(message)

    def load_logs_from_db(self):
        logs = get_logs_from_db()
        for timestamp, message in logs:
            log_message = f"[{timestamp}] {message}"
            self.update_log(log_message, QColor("dark"), QColor("gray"))