# This file is part of Gajim.
#
# SPDX-License-Identifier: GPL-3.0-only


from __future__ import annotations

from typing import Any
from typing import cast
from typing import Literal
from typing import TYPE_CHECKING

import datetime
import gc
import logging
import os
import pprint
import sys
import weakref
import xml.etree.ElementTree as ET
from collections.abc import Iterator
from functools import partial
from functools import wraps
from pathlib import Path

import cairo
from gi.repository import Adw
from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Pango
from packaging.requirements import Requirement

from gajim.common import app
from gajim.common import types
from gajim.common.configpaths import get_ui_path
from gajim.common.const import AvatarSize
from gajim.common.const import LINUX_EXECUTABLE_EXTENSIONS
from gajim.common.const import MACOS_EXECUTABLE_EXTENSIONS
from gajim.common.const import MAX_MESSAGE_CORRECTION_DELAY
from gajim.common.const import WINDOWS_EXECUTABLE_EXTENSIONS
from gajim.common.i18n import _
from gajim.common.modules.contacts import BareContact
from gajim.common.modules.contacts import GroupchatContact
from gajim.common.modules.contacts import GroupchatParticipant
from gajim.common.storage.archive import models as mod
from gajim.common.storage.archive.const import ChatDirection
from gajim.common.storage.archive.const import MessageState
from gajim.common.storage.archive.const import MessageType
from gajim.common.styling import PlainBlock
from gajim.common.util.datetime import utc_now
from gajim.common.util.decorators import catch_exceptions
from gajim.common.util.uri import geo_provider_from_location
from gajim.common.util.uri import GeoUri
from gajim.common.util.uri import InvalidUri
from gajim.common.util.uri import parse_uri
from gajim.common.util.uri import Uri
from gajim.common.util.uri import UriT
from gajim.common.util.uri import XmppIri

from gajim.gtk.alert import ConfirmationAlertDialog
from gajim.gtk.const import GDK_MEMORY_DEFAULT

if sys.platform == "darwin" or TYPE_CHECKING:
    from AppKit import NSWorkspace
    from Foundation import NSURL

log = logging.getLogger("gajim.gtk.util")


def get_gtk_version() -> str:
    return "%i.%i.%i" % (
        Gtk.get_major_version(),
        Gtk.get_minor_version(),
        Gtk.get_micro_version(),
    )


def get_adw_version() -> str:
    return "%i.%i.%i" % (
        Adw.get_major_version(),
        Adw.get_minor_version(),
        Adw.get_micro_version(),
    )


def gi_gui_package_version(requirement: str):
    req = Requirement(requirement)
    match req.name:
        case "Gtk":
            version = get_gtk_version()
        case "Adw":
            version = get_adw_version()
        case _:
            raise ValueError("Unknown lib name: %s" % req.name)

    return req.specifier.contains(version)


def scroll_to(widget: Gtk.ScrolledWindow, pos: Literal["top", "bottom"]) -> bool:
    """Scrolls to `pos` of a GtkScrolledWindow.

    Args:
        widget (GtkScrolledWindow)

    Returns:
        bool: The return value is False so it can be used with GLib.idle_add.
    """
    adj_v = widget.get_vadjustment()
    if adj_v is None:  # type: ignore
        # This can happen when the Widget is already destroyed when called
        # from GLib.idle_add
        return False

    scroll_pos = 0
    if pos == "bottom":
        scroll_pos = adj_v.get_upper() - adj_v.get_page_size()
    adj_v.set_value(scroll_pos)

    adj_h = widget.get_hadjustment()
    adj_h.set_value(0)
    return False


def at_the_end(widget: Gtk.ScrolledWindow) -> bool:
    """Determines if a Scrollbar in a GtkScrolledWindow is at the end.

    Args:
        widget (GtkScrolledWindow)

    Returns:
        bool: The return value is True if at the end, False if not.
    """
    adj_v = widget.get_vadjustment()
    max_scroll_pos = adj_v.get_upper() - adj_v.get_page_size()
    return adj_v.get_value() == max_scroll_pos


def ensure_not_destroyed(func: Any) -> Any:
    @wraps(func)
    def func_wrapper(self: Any, *args: Any, **kwargs: Any):
        if self._destroyed:  # pylint: disable=protected-access
            return None
        return func(self, *args, **kwargs)

    return func_wrapper


def get_contact_name_for_message(
    db_row: mod.Message, contact: types.ChatContactT
) -> str:
    if isinstance(contact, BareContact) and contact.is_self:
        return _("Me")

    if db_row.type == MessageType.CHAT:
        if db_row.direction == ChatDirection.INCOMING:
            return contact.name

        return app.get_client(contact.account).get_own_contact().name

    elif db_row.type == MessageType.GROUPCHAT:
        resource = db_row.resource
        if resource is None:
            # Fall back to MUC name if contact name is None
            # (may be the case for service messages from the MUC)
            return contact.name
        return resource

    elif db_row.type == MessageType.PM:
        if occupant := db_row.occupant:
            if name := occupant.nickname:
                return name

        if db_row.resource is None:
            if db_row.direction == ChatDirection.OUTGOING:
                return _("Me")
            # This should never happen better degrade gracefully
            return "Unknown"
        return db_row.resource

    else:
        raise ValueError


def get_avatar_for_message(
    db_row: mod.Message, contact: types.ChatContactT, scale: int, size: AvatarSize
) -> Gdk.Texture | None:
    if db_row.direction == ChatDirection.OUTGOING:
        return app.app.avatar_storage.get_own_avatar_texture(
            contact.account, size, scale
        )

    match db_row.type:
        case MessageType.GROUPCHAT | MessageType.PM:
            if db_row.resource is None:
                # Message from Groupchat itself
                assert isinstance(contact, GroupchatContact)
                return contact.get_avatar(size, scale)

            return app.app.avatar_storage.get_occupant_texture(
                db_row.remote.jid, db_row.occupant or db_row.resource, size, scale
            )

        case MessageType.CHAT:
            if isinstance(contact, BareContact):
                return contact.get_avatar(size, scale, add_show=False)
            log.warning("Unexpected contact type %r, unable to get avatar", contact)
            return None

        case _:
            raise ValueError(f"Unhandled type: {db_row.type}")


def is_message_correctable(message: mod.Message) -> bool:
    if any([message.retraction, message.moderation, message.error]):
        return False

    if (
        message.direction == ChatDirection.INCOMING
        or message.state == MessageState.PENDING
    ):
        return False

    if not message.text:
        return False

    min_time = utc_now() - datetime.timedelta(seconds=MAX_MESSAGE_CORRECTION_DELAY)
    return message.timestamp > min_time


def make_pango_attributes(block: PlainBlock) -> Pango.AttrList:
    attrlist = Pango.AttrList()
    for span in block.spans:
        attr = get_style_attribute_with_name(span.name)
        attr.start_index = span.start_byte
        attr.end_index = span.end_byte
        attrlist.insert(attr)
    return attrlist


_grapheme_buffer = Gtk.TextBuffer()


def get_first_graphemes(text: str, n: int) -> str:
    # This should be possible with lower-level APIs like Pango.break_* or
    # Pango.get_log_attrs, but their Python bindings seem totally broken.
    # The reuse of one global buffer is to mitigate very probable memory leaks.
    _grapheme_buffer.set_text(text)
    cursor = _grapheme_buffer.get_start_iter()
    cursor.forward_cursor_positions(n)
    return _grapheme_buffer.get_slice(_grapheme_buffer.get_start_iter(), cursor, False)


def get_first_grapheme(text: str) -> str:
    return get_first_graphemes(text, 1)


def get_style_attribute_with_name(name: str) -> Pango.Attribute:
    if name == "strong":
        return Pango.attr_weight_new(Pango.Weight.BOLD)

    if name == "strike":
        return Pango.attr_strikethrough_new(True)

    if name == "emphasis":
        return Pango.attr_style_new(Pango.Style.ITALIC)

    if name == "pre":
        return Pango.attr_family_new("monospace")

    raise ValueError("unknown attribute %s" % name)


def get_key_theme() -> str | None:
    settings = Gtk.Settings.get_default()
    if settings is None:
        return None
    return settings.get_property("gtk-key-theme-name")


def allow_send_message(has_text: bool, contact: types.ChatContactT) -> bool:
    if isinstance(contact, GroupchatContact):
        joined = contact.is_joined

        is_visitor = False
        if joined:
            self_contact = contact.get_self()
            assert self_contact
            is_visitor = self_contact.role.is_visitor

        return bool(has_text and joined and not is_visitor)

    if isinstance(contact, GroupchatParticipant):
        if not contact.is_available:
            return False

        return bool(has_text and contact.room.is_joined)

    # BareContact
    online = app.account_is_connected(contact.account)
    return bool(online and has_text)


def iterate_listbox_children(listbox: Gtk.ListBox) -> Iterator[Gtk.Widget]:
    index = 0
    while child := listbox.get_row_at_index(index):
        yield child
        index += 1


def container_remove_all(container: Any) -> None:
    while child := container.get_first_child():
        container.remove(child)


def clear_listbox(listbox: Gtk.ListBox) -> None:
    """Gtk.ListBox.remove_all() does not work if backed by a model."""
    for row in iterate_listbox_children(listbox):
        listbox.remove(row)


def get_listbox_row_count(listbox: Gtk.ListBox) -> int:
    return len(list(iterate_listbox_children(listbox)))


def iterate_children(widget: Gtk.Widget) -> Iterator[Gtk.Widget]:
    child = widget.get_first_child()
    if child is None:
        return
    yield child

    while child := child.get_next_sibling():
        yield child


# GTK maintains this as a single internal instance shared across all windows,
# lazily parented onto whichever toplevel most recently queried a tooltip
# It's not owned by the widget being unrooted, so it must not be tracked as
# one of its children when checking for finalization.
_GTK_INTERNAL_SINGLETON_WIDGETS = frozenset({"GtkTooltipWindow"})


def iterate_widget_tree(
    widget: Gtk.Widget, parent: str | None = None, only_children: bool = False
) -> Iterator[tuple[Gtk.Widget, str | None]]:
    if not only_children:
        yield widget, parent

    if parent is None:
        parent = widget.__class__.__name__
    else:
        parent += f" -> {widget.__class__.__name__}"

    child = widget.get_first_child()
    if child is None:
        return

    if child.__class__.__name__ not in _GTK_INTERNAL_SINGLETON_WIDGETS:
        yield from iterate_widget_tree(child, parent)

    while child := child.get_next_sibling():
        if child.__class__.__name__ in _GTK_INTERNAL_SINGLETON_WIDGETS:
            continue
        yield from iterate_widget_tree(child, parent)


def convert_surface_to_texture(surface: cairo.ImageSurface) -> Gdk.Texture:
    memoryv = surface.get_data()
    assert memoryv is not None
    return Gdk.MemoryTexture.new(
        width=surface.get_width(),
        height=surface.get_height(),
        format=GDK_MEMORY_DEFAULT,
        bytes=GLib.Bytes.new(memoryv.tobytes()),
        stride=surface.get_stride(),
    )


def convert_texture_to_surface(texture: Gdk.Texture) -> cairo.ImageSurface:
    downloader = Gdk.TextureDownloader.new(texture)
    gbytes, stride = downloader.download_bytes()
    bytes_ = gbytes.get_data()
    assert bytes_ is not None
    array = bytearray(bytes_)

    surface = cairo.ImageSurface.create_for_data(
        array,
        cairo.Format.ARGB32,
        texture.get_width(),
        texture.get_height(),
        stride,
    )
    return surface


def convert_py_to_glib_datetime(dt: datetime.datetime | datetime.date) -> GLib.DateTime:
    if type(dt) is datetime.date:
        dt = datetime.datetime(
            year=dt.year,
            month=dt.month,
            day=dt.day,
            hour=0,
            minute=0,
            second=0,
            tzinfo=datetime.UTC,
        )

    g_dt = GLib.DateTime.new_from_iso8601(dt.isoformat())
    assert g_dt is not None
    return g_dt


def get_ui_string(filename: str) -> bytes:
    path = get_ui_path(filename)

    if sys.platform != "win32":
        return path.read_bytes()

    tree = ET.parse(path)
    for node in tree.findall(".//*[@translatable='yes']"):
        node.text = _(node.text) if node.text else ""
        del node.attrib["translatable"]
    return ET.tostring(tree.getroot(), method="xml")


@catch_exceptions
def open_uri(uri: UriT | str) -> None:
    if isinstance(uri, str):
        uri = parse_uri(uri)

    match uri:
        case InvalidUri():
            log.warning("Failed to open uri: %s", uri.error)

        case XmppIri():
            app.window.open_xmpp_iri(uri)

        case GeoUri():
            if Gio.AppInfo.get_default_for_uri_scheme("geo"):
                open_uri_externally(uri.uri)
            else:
                open_uri(geo_provider_from_location(uri.lat, uri.lon))

        case Uri():
            open_uri_externally(uri.uri)


def open_uri_externally(uri: str) -> None:
    launcher = Gtk.UriLauncher(uri=uri)
    try:
        launcher.launch(app.window)
    except Exception as error:
        log.warning(
            "open_uri_externally: Couldn't launch default for %s: %s", uri, error
        )


def is_file_extension_executable(path: Path) -> bool:
    if not path.suffix:
        return False

    suffix_lowercase = path.suffix[1:].lower()

    match sys.platform:
        case "win32":
            return suffix_lowercase in WINDOWS_EXECUTABLE_EXTENSIONS
        case "darwin":
            return suffix_lowercase in MACOS_EXECUTABLE_EXTENSIONS
        case "linux":
            return suffix_lowercase in LINUX_EXECUTABLE_EXTENSIONS
        case _:
            return False


@catch_exceptions
def open_file(path: Path, *, show_in_folder: bool = False) -> None:
    if not path.exists():
        log.warning("Unable to open file, path %s does not exist", path)
        return

    path_absolute = path.resolve()

    def _on_open_confirm() -> None:
        launcher.launch(app.window)

    launcher = Gtk.FileLauncher(file=Gio.File.new_for_path(str(path_absolute)))
    try:
        if show_in_folder:
            if (
                sys.platform == "darwin"
            ):  # Implemented as workaround for https://gitlab.gnome.org/GNOME/gtk/-/issues/8070
                assert NSWorkspace is not None and NSURL is not None
                url = NSURL.fileURLWithPath_(str(path_absolute))
                NSWorkspace.sharedWorkspace().activateFileViewerSelectingURLs_([url])
            else:
                launcher.open_containing_folder(app.window)
        else:
            if is_file_extension_executable(path_absolute):
                ConfirmationAlertDialog(
                    _("Open File?"),
                    _(
                        "Opening this file may be harmful for your computer. Do you really want to open this file?"
                    ),
                    confirm_label=_("_Open"),
                    appearance="destructive",
                    callback=_on_open_confirm,
                )
            else:
                launcher.launch(app.window)
    except Exception as error:
        log.warning("Unable to open file: %s", error)


def remove_css_class(widget: Gtk.Widget, css_class_name: str) -> None:
    for css_class in list(widget.get_css_classes()):
        if css_class_name in css_class:
            widget.remove_css_class(css_class)


def transform_to_inverted_bool(_binding: GObject.Binding, value: GLib.Variant) -> bool:
    return not value.unpack()


class ObjTracker:
    def __init__(self) -> None:
        self._gobjects: list[str] = []
        self._pyobjects: dict[str, Any] = {}

    def get_count(self) -> int:
        return len(self._gobjects)

    def track(self, obj: GObject.Object, path: str | None) -> None:
        if path is None:
            full_path = f"({id(obj)}) {obj.__class__.__name__}"
        else:
            full_path = f"({id(obj)}) {path} -> {obj.__class__.__name__}"

        obj.weak_ref(partial(self._gobjects.remove, full_path))
        self._gobjects.append(full_path)

        finalizer = weakref.finalize(obj, partial(self._pyobjects.pop, full_path))
        self._pyobjects[full_path] = finalizer

    def iter_pyobjects(self) -> Iterator[tuple[str, Any]]:
        yield from self._pyobjects.items()

    def iter_gobjects(self) -> Iterator[str]:
        yield from self._gobjects

    def pyobj_finalized(self) -> bool:
        return not bool(self._pyobjects)

    def gobj_finalized(self) -> bool:
        return not bool(self._gobjects)

    def get_pyobject_leaks(self) -> str:
        def is_finalizer_ref(ref: Any) -> bool:
            try:
                return isinstance(ref[2][0], str)
            except Exception:
                return False

        log_string = ""
        for path, finalizer in self.iter_pyobjects():
            tup = finalizer.peek()
            if tup is None:
                continue

            log_string += f"{path} not finalized\n"
            log_string += "References:"

            for ref in gc.get_referrers(tup[0]):
                if is_finalizer_ref(ref):
                    continue
                if isinstance(ref, dict):
                    ref = cast(Any, ref)
                    log_string += f"{pprint.pformat(ref)}\n"
                else:
                    log_string += f"{ref}\n"

        return log_string

    def get_gobject_leaks(self) -> str:
        return "\n".join(self.iter_gobjects())


def check_finalize(obj: GObject.Object, only_children: bool = False) -> None:
    if "GAJIM_LEAK" not in os.environ:
        return

    logger = logging.getLogger("gajim.leak")
    parent_obj = obj.__class__.__name__

    if isinstance(obj, Gtk.Widget):
        objs = iterate_widget_tree(obj, only_children=only_children)
    else:
        objs = [(obj, None)]

    tracker = ObjTracker()

    for _obj, path in objs:
        tracker.track(_obj, path)
    del objs

    obj_count = tracker.get_count()
    if not obj_count:
        return

    def check_finalized():
        gc.collect()

        if tracker.pyobj_finalized():
            logger.info(
                "%s (Python Object) successful finalized (total: %s)",
                parent_obj,
                obj_count,
            )
        else:
            logger.warning(
                "%s (Python Object) failed to finalize (total: %s)\n%s",
                parent_obj,
                obj_count,
                tracker.get_pyobject_leaks(),
            )

        if tracker.gobj_finalized():
            logger.info(
                "%s (GObject) successful finalized (total: %s)", parent_obj, obj_count
            )
        else:
            logger.warning(
                "%s (GObject) failed to finalize (total: %s)\n%s",
                parent_obj,
                obj_count,
                tracker.get_gobject_leaks(),
            )

    GLib.timeout_add_seconds(2, check_finalized)
