# standard
import json
from pathlib import Path

# PyQGIS
from qgis.PyQt.QtCore import QByteArray, QUrl

# plugin
from oslandia.constants import UTM_CONTENT_ISSUEBROWSER
from oslandia.toolbelt import PlgLogger, PlgOptionsManager
from oslandia.toolbelt.cache_manager import CacheManager
from oslandia.toolbelt.network_manager import NetworkRequestsManager


class UploadRequestManager:
    def __init__(self):
        """
        Helper for stored_data request

        """
        self.log = PlgLogger().log
        self.ntwk_requester_blk = NetworkRequestsManager()
        self.plg_settings = PlgOptionsManager.get_plg_settings()
        self.cache_manager = CacheManager(".oslandia", "cache")

    def get_base_url(self, project_id: int) -> str:
        """
        Get base url for project

        Args:
            project_id: (int) project id

        Returns: url for project

        """
        return f"{self.plg_settings.gitlab_api_url_base}projects/{project_id}"

    def get_upload(self, project_id: int, upload_secret_and_name: str) -> QByteArray:
        """Get upload from gitlab.

        :param project_id: project id
        :type project_id: int
        :param upload_secret_and_name: "/uploads/{upload_secret}/{filename}" string
        :type upload_secret_and_name: str

        :return: upload content
        :rtype: QByteArray
        """
        self.log(
            f"{__name__}.get_upload(project:{project_id},upload:{upload_secret_and_name})"
        )
        cache_file = self.cache_manager.get_project_upload_cache_path(
            project_id=project_id, upload_secret_and_name=upload_secret_and_name
        )
        req_reply = self.cache_manager.load_cache_file_content(cache_file)
        if not req_reply:
            # send request
            req_reply = self.ntwk_requester_blk.get_url(
                QUrl(f"{self.get_base_url(project_id)}/{upload_secret_and_name}"),
                self.plg_settings.authentification_config_id,
                debug_log_response=False,
                caller=UTM_CONTENT_ISSUEBROWSER,
            )
            self.cache_manager.save_cache_file_content(cache_file, req_reply)

        return req_reply

    def create_upload(self, project_id: int, file_path: Path) -> str:
        """Create upload and return markdown string

        :param project_id: project id
        :type project_id: int
        :param file_path: file path
        :type file_path: Path
        :return: markdown string
        :rtype: str
        """
        self.log(f"{__name__}.create_upload() {project_id=} {file_path=}")

        req_reply = self.ntwk_requester_blk.post_file(
            url=QUrl(self.get_base_url(project_id) + "/uploads"),
            file_path=file_path,
            config_id=self.plg_settings.authentification_config_id,
            caller=UTM_CONTENT_ISSUEBROWSER,
        )
        if req_reply:
            data = json.loads(req_reply.data().decode("utf-8"))
            return data["markdown"]
        else:
            return ""
