# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial

from typing import List, Optional

from PySide6.QtCore import (QDir, QSignalBlocker, Signal,
                            Slot)
from PySide6.QtWidgets import (QGroupBox, QHBoxLayout, QListWidget,
                               QListWidgetItem, QPushButton, QVBoxLayout,
                               QWidget)

from utils import launch_file


class ListChooser(QGroupBox):
    """Presents a list of files/directories to which a user can add"""

    changed = Signal()

    def __init__(self, title, parent: Optional[QWidget] = None):
        super(ListChooser, self).__init__(title, parent)
        main_layout = QHBoxLayout(self)
        self._list = QListWidget(self)
        self._list.currentItemChanged.connect(self._current_item_changed)
        self._list.itemActivated.connect(self._item_activated)
        main_layout.addWidget(self._list)

        vbox_layout = QVBoxLayout()
        main_layout.addLayout(vbox_layout)
        self._addButton = QPushButton("Add...")
        vbox_layout.addWidget(self._addButton)
        self._addButton.clicked.connect(self._add)
        self._removeButton = QPushButton("Remove")
        self._removeButton.setEnabled(False)
        self._removeButton.clicked.connect(self._remove_current)
        vbox_layout.addWidget(self._removeButton)
        vbox_layout.addStretch()

    # Overwrite to return a file
    def prompt_file(self) -> Optional[str]:
        pass

    def files(self) -> List[str]:
        result = []
        for i in range(self._list.count()):
            f = QDir.fromNativeSeparators(self._list.item(i).text())
            result.append(f)
        return result

    def is_empty(self) -> bool:
        return self._list.count() == 0

    def count(self) -> int:
        return self._list.count()

    def set_files(self, files: List[str]) -> None:
        with QSignalBlocker(self):
            self._list.clear()
            for f in files:
                self._list.addItem(QDir.toNativeSeparators(f))

    @Slot()
    def _add(self) -> None:
        file = self.prompt_file()
        if file and file not in self.files():
            self._list.addItem(file)
            self.changed.emit()

    @Slot(QListWidgetItem, QListWidgetItem)
    def _current_item_changed(self, current: QListWidgetItem,
                              previous: QListWidgetItem) -> None:
        self._removeButton.setEnabled(current is not None)

    @Slot()
    def _remove_current(self) -> None:
        row = self._list.row(self._list.currentItem())
        if row >= 0:
            self._list.takeItem(row)
            self.changed.emit()

    @Slot(QListWidgetItem)
    def _item_activated(self, item: QListWidgetItem) -> None:
        f = QDir.fromNativeSeparators(item.text())
        launch_file(f)
