from __future__ import annotations

import datetime
import typing
import uuid

if typing.TYPE_CHECKING:
    import file_widgets

import pydantic
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QMessageBox, QWidget
from request_client import RequestClient
from utils import resource_path


class Folder(pydantic.BaseModel):
    folder_id: uuid.UUID
    owner_id: int
    folder_name: str
    created_at: datetime.datetime

    def name(self) -> str:
        return self.folder_name

    def delete(self) -> None:
        import sync

        sync.SyncData.delete(self.folder_id)
        response = RequestClient().client.delete(
            "/folders", params={"folder_id": self.folder_id}
        )
        if not response:
            QMessageBox.warning(None, "Error deleting folder", response.text)

    def details(self, _: file_widgets.FileListWidget) -> QWidget:
        import folder_info

        return folder_info.FolderInfoWidget(self)

    def icon(self) -> QIcon:
        return QIcon(resource_path("assets/folder.png"))

    def double_click(self, list: file_widgets.FileListWidget) -> None:
        import file_widgets

        list.responses.append(file_widgets.ListResponse.get(self.folder_id))
        list.update()

    @staticmethod
    def create(name: str, parent_id: uuid.UUID) -> uuid.UUID:
        try:
            response = RequestClient().client.post(
                "/folders",
                json={
                    "folder_name": name,
                    "parent_folder_id": str(parent_id),
                },
            )
            if not response.is_success:
                QMessageBox.warning(
                    None, "Error creating folder", response.text
                )
            return uuid.UUID(response.text.strip('"'))
        except Exception as e:
            QMessageBox.warning(None, "Error creating the folder", str(e))
