# Copyright (C) 2024 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
import logging
from pathlib import Path
from typing import Optional


class DesignStudioProject:
    """
    Class to handle Design Studio projects. The project structure is as follows:
    - Python folder
        - autogen folder
            - settings.py
            - resources.py (Compiled resources)
        - main.py
    <ProjectName>.qrc (Resources collection file)
    <ProjectName>.qmlproject
    <ProjectName>.qmlproject.qtds (should be added to .gitignore)
    ... Other files and folders ...
    """

    def __init__(self, main_file: Path):
        self.main_file = main_file
        self.project_dir = main_file.parent.parent
        self.compiled_resources_file = self.main_file.parent / "autogen" / "resources.py"

    @staticmethod
    def is_ds_project(main_file: Path) -> bool:
        return bool(*main_file.parent.parent.glob("*.qmlproject"))

    def compiled_resources_available(self) -> bool:
        """
        Returns whether the resources of the project have been compiled into a .py file.
        TODO: Make the resources path configurable. Wait for the pyproject TOML configuration
        """
        return self.compiled_resources_file.exists()

    def get_resource_file_path(self) -> Optional[Path]:
        """
        Return the path to the *.qrc resources file from the project root folder.
        If not found, log an error message and return None
        If multiple files are found, log an error message and return None
        If a single file is found, return its path
        """
        resource_files = list(self.project_dir.glob("*.qrc"))
        if not resource_files:
            logging.error("No *.qrc resources file found in the project root folder")
            return None
        if len(resource_files) > 1:
            logging.error("Multiple *.qrc resources files found in the project root folder")
            return None
        return resource_files[0]

    def get_compiled_resources_file_path(self) -> Path:
        """
        Return the path of the output file generated by compiling the *.qrc resources file
        """
        # TODO: make this more robust and configurable. Wait for the pyproject TOML configuration
        return self.main_file.parent / "autogen" / "resources.py"

    def clean(self):
        """
        Remove the compiled resources file if it exists
        """
        self.compiled_resources_file.unlink(missing_ok=True)
