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

import os
from typing import List

from PySide6.QtCore import QObject, Signal, Slot
from PySide6.QtGui import QAction
from PySide6.QtWidgets import QMenu


class RecentMenu(QObject):
    """Recent Files menu."""

    MAX_RECENT_FILES = 10

    load = Signal(str)

    def __init__(self, parent: QMenu):
        super(RecentMenu, self).__init__(parent)
        self._files: List[str] = []
        self._menu = parent.addMenu('Recent Files')
        self._actions: List[QAction] = []
        for _ in range(RecentMenu.MAX_RECENT_FILES):
            a = self._menu.addAction('f')
            a.triggered.connect(self._triggered)
            self._actions.append(a)

        self._menu.aboutToShow.connect(self._update_menu)

    def files(self) -> List[str]:
        """Return the current list"""
        return self._files

    def set_files(self, fl: List[str]) -> None:
        """Set the list (restore from settings)"""
        self._files = []
        for f in fl:
            if os.path.isfile(f):
                self._files.append(f)
            if len(self._files) >= RecentMenu.MAX_RECENT_FILES:
                break

    @Slot(str)
    def add_file(self, f: str) -> None:
        """Add a file (when unloading)"""
        if f and f not in self._files:
            self._files.insert(0, f)
            while len(self._files) > RecentMenu.MAX_RECENT_FILES:
                self._files.pop()

    @Slot()
    def _update_menu(self) -> None:
        i = 0
        for f in self._files:
            if os.path.isfile(f):
                a = self._actions[i]
                a.setText(os.path.basename(f))
                a.setData(f)
                a.setVisible(True)
                i += 1
        while i < RecentMenu.MAX_RECENT_FILES:
            self._actions[i].setVisible(False)
            i += 1

    @Slot()
    def _triggered(self):
        file = self.sender().data()
        self.load.emit(file)
