from pathlib import Path
from typing import List

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont
from PyQt6.QtWidgets import (
    QFileDialog,
    QHBoxLayout,
    QLabel,
    QPushButton,
    QScrollArea,
    QVBoxLayout,
    QWidget,
)

from app import constants as c
from app.exceptions import OpenFileError
from app.paths import BASE_DIR

from .base import DialogWindow


class BrowseFileWindow(DialogWindow):
    """
    Window for choosing a video files to be processed.
    """

    INITIAL_DIR = BASE_DIR

    def __init__(self) -> None:
        super().__init__((600, 350), title="Vyberte si video")
        self.file_paths: List[Path] = []
        self._add_label()
        self._add_file_browser()
        self._add_chosen_file_list()
        self._add_button_next()

    def _add_label(self) -> None:
        label = QLabel("Detektor pohybů")
        label.setFont(QFont("Arial", 22, 600))
        label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.general_layout.addWidget(label)

    def _add_file_browser(self) -> None:
        browse_widget = QWidget()
        layout = QHBoxLayout(browse_widget)
        self.browse_btn = QPushButton("Procházet", self)
        self.browse_btn.setFixedWidth(100)
        self.browse_btn.clicked.connect(self._ask_filepath)
        layout.addWidget(self.browse_btn)
        self.general_layout.addWidget(browse_widget)

    def _add_chosen_file_list(self) -> None:
        self.scrollable_area = QScrollArea()
        self.scrollable_area.setWidgetResizable(True)
        file_list_widget = QWidget()
        self.file_list_layout = QVBoxLayout(file_list_widget)
        self.file_list_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.scrollable_area.setWidget(file_list_widget)
        self.general_layout.addWidget(self.scrollable_area)
        self.scrollable_area.hide()

    def _sync_chosen_file_list(self) -> None:
        if self.file_paths:
            self.scrollable_area.show()
        else:
            self.scrollable_area.hide()
        # clear layout
        for i in reversed(range(self.file_list_layout.count())):
            self.file_list_layout.itemAt(i).widget().setParent(None)
        # add new items
        file_list_text = "<br>".join([str(file_path) for file_path in self.file_paths])
        self.file_list_layout.addWidget(QLabel(file_list_text))

    def _ask_filepath(self) -> None:
        file_paths, _ = QFileDialog.getOpenFileNames(
            self,
            "Choose a video file",
            str(self.INITIAL_DIR),
            _get_browse_file_format_filter(),
        )
        if file_paths:
            self.file_paths = [Path(file_path) for file_path in file_paths]
        self._sync_chosen_file_list()

    def _add_button_next(self) -> None:
        control_widget = QWidget()
        layout = QHBoxLayout(control_widget)
        self.next_btn = QPushButton("Další", self)
        self.next_btn.clicked.connect(self._check_file)
        layout.setAlignment(Qt.AlignmentFlag.AlignRight)
        layout.addWidget(self.next_btn)
        self.general_layout.addWidget(control_widget)

    def _check_file(self) -> None:
        file_paths = self.file_paths
        if not file_paths:
            raise OpenFileError("Nebyl vybrán žádný soubor")
        for file_path in file_paths:
            if not file_path.exists():
                raise OpenFileError(f"Soubor {file_path} neexistuje")
            extension = file_path.suffix
            if extension not in c.VIDEO_FILE_EXTENSIONS:
                raise OpenFileError(
                    f'Soubor {file_path} s příponou "{extension}" není podporován'
                )
        self.next_window()


def _get_browse_file_format_filter() -> str:
    return " ".join(f"*{extension}" for extension in c.VIDEO_FILE_EXTENSIONS)
