# -*- coding: utf8 -*-

"""Common web components."""

from __future__ import annotations

__all__ = ['ExtendedWebEnginePage']

import typing

from qtpy import QtCore
from qtpy import QtWebEngineWidgets

from . import links


class ExtendedWebEnginePage(QtWebEngineWidgets.QWebEnginePage):
    """Custom :class:`~QWebEnginePage` to open links in default browser."""

    sig_navigator_link_requested = QtCore.Signal(object)

    def __init__(self, *args: typing.Any, origin: str | None = None, **kwargs: typing.Any) -> None:
        """Initialize new instance of :class:`~ExtendedWebEnginePage`."""
        super().__init__(*args, **kwargs)

        self.__origin: typing.Final[str | None] = origin

        self.settings().setAttribute(QtWebEngineWidgets.QWebEngineSettings.ShowScrollBars, False)

    def acceptNavigationRequest(  # pylint: disable=invalid-name
          self,
            url: QtCore.QUrl,
            _type: int,
            isMainFrame: bool,  # pylint: disable=invalid-name
    ) -> bool:
        """Open links in external browser."""
        link: str = url.toString()

        if link.startswith('navigator://'):
            self.sig_navigator_link_requested.emit(links.NavigatorLink.parse(link))
            return False

        if isMainFrame and (_type == QtWebEngineWidgets.QWebEnginePage.NavigationTypeLinkClicked):
            links.open_link(url, origin=self.__origin)
            return False

        return super().acceptNavigationRequest(url, _type, isMainFrame)
