import sys
import os
import time
from PyQt5.QtWidgets import (
    QApplication,
    QMainWindow,
    QTabWidget,
    QWidget,
    QVBoxLayout,
    QLabel,
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QObject, QFileSystemWatcher
from PyQt5.QtGui import QIcon
from src.gui import qt_settings as qts

# Импортируйте ваш класс `app` здесь
# Предполагается, что класс `app` предоставляет интерфейс для отображения данных
# Если `app` не предоставляет виджет, возможно, потребуется его модифицировать
from src.gui.app import tabWidgetGenerator


class DirectoryWatcher(QObject):

    file_created = pyqtSignal(str)

    def __init__(self, directory_path):
        super().__init__()
        self.directory_path = directory_path
        self.watcher = QFileSystemWatcher()
        self.watcher.addPath(self.directory_path)
        self.existing_files = set(os.listdir(self.directory_path))
        self.watcher.directoryChanged.connect(self.on_directory_changed)
      

    def on_directory_changed(self, _):
        try:
            current_files = set(os.listdir(self.directory_path))
            new_files = current_files - self.existing_files
            self.existing_files = current_files
            for file in new_files:
                if file.lower().endswith(".csv"):
                    full_path = os.path.join(self.directory_path, file)
                    self.file_created.emit(full_path)
        except Exception as e:
            print(f"Ошибка при обработке изменений директории: {e}")


class MainWindow(QMainWindow):
    def __init__(self, directory_to_watch):
        super().__init__()
        self.setWindowTitle("Мониторинг CSV-файлов")
        self.setGeometry(100, 100, 800, 600)

        self.tabs = QTabWidget()
        self.tabs.setStyleSheet(qts.dark_style)
        self.tabGen = tabWidgetGenerator(directory_to_watch)
        self.handle_new_file()
        self.setCentralWidget(self.tabs)

        # self.setWindowIcon(QIcon("path_to_icon.png"))
        self.start_directory_watcher(directory_to_watch)
        

    def start_directory_watcher(self, directory_path):
        self.watcher_thread = QThread()
        self.watcher = DirectoryWatcher(directory_path)
        self.watcher.moveToThread(self.watcher_thread)

        self.watcher.file_created.connect(self.handle_new_file)
        self.watcher_thread.started.connect(self.watcher.on_directory_changed)

        self.watcher_thread.start()

    def handle_new_file(self, file_path = None):
        time.sleep(0.2)
        if file_path:
            file_name = os.path.basename(file_path)
        else:
            file_path = None
            file_name = 'Ideal'

        tab_widget = self.tabGen.get_widget(path=file_path)

        tab = QWidget()
        layout = QVBoxLayout()
        layout.addWidget(tab_widget)

        label = QLabel(f"{file_name}")
        label.setAlignment(Qt.AlignCenter)
        layout.addWidget(label)
        tab.setLayout(layout)

        self.tabs.addTab(tab, file_name)

    def closeEvent(self, event):
        self.watcher_thread.quit()
        self.watcher_thread.wait()
        event.accept()


def main():
    directory_to_watch = "D:/downloads/a22"

    if not os.path.isdir(directory_to_watch):
        print(f"Директория не найдена: {directory_to_watch}")
        sys.exit(1)

    app_instance = QApplication(sys.argv)
    window = MainWindow(directory_to_watch)
    window.show()
    sys.exit(app_instance.exec_())


if __name__ == "__main__":
    main()
