# widgets/weblinkactionrow.py
#
# Copyright 2020-2025 Fabio Comuni, et al.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from os import path
from urllib.parse import urlparse
import html

from gi.repository import Gio
from gi.repository import Gtk
from gi.repository import Adw

from ..utils import clean_markup


class WebLinkActionRow(Adw.ActionRow):
    def __init__(self, title, url, icontype=None, **kwargs):
        opts = dict(activatable=True, selectable=False)
        opts.update(kwargs)
        super().__init__(**opts)
        self.url = url
        if title is None:
            title = path.basename(url)
        self.set_title(clean_markup(html.unescape(title)))
        self.set_subtitle(url)

        # if icontype is None:
        icontype = "text/html"
        parsedurl = urlparse(url)
        if parsedurl.path:
            ftype, _ = Gio.content_type_guess(parsedurl.path)
            fmaj, fmin = ftype.split("/")
            if fmaj in ('text', 'video', 'audio', 'image'):
                icontype = ftype
            if fmin == 'pdf' or 'document' in fmin:
                icontype = ftype

        self.content_type = icontype
        ficon = Gio.content_type_get_icon(icontype)

        image = Gtk.Image.new_from_gicon(ficon)
        image.set_icon_size(Gtk.IconSize.LARGE)
        self.add_prefix(image)


def weblinkactionrowactivated(listbox, actionrow):
    appinfo = Gio.app_info_get_default_for_type(actionrow.content_type, True)
    if appinfo is not None:
        appinfo.launch_uris([actionrow.url], None)
    else:
        Gio.app_info_launch_default_for_uri(actionrow.url, None)
