# message.py
#
# Copyright 2024 Lucas Fryzek
#
# 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 <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later
from gi.repository import Adw, Gtk, GLib, Pango

import re

re_url_exp = r"([A-Za-z0-9_.\-~/@]+://[A-Za-z0-9_.\-~/@?=&%#]+)"
re_url = re.compile(re_url_exp)

@Gtk.Template(resource_path='/com/fryzekconcepts/weegtk/gtk/message.ui')
class WeegtkMessage(Gtk.Box):
    __gtype_name__ = 'WeegtkMessage'

    username = Gtk.Template.Child()
    avatar = Gtk.Template.Child()
    message_list = Gtk.Template.Child()

    def __init__(self, username="username", messages=[], **kwargs):
        super().__init__(**kwargs)

        data = {
            "type": "empty"
        }
        self.set_contents(data)

    def parse_message(self, message, pos=0):
        res = re_url.search(message, pos)

        if res != None:
            res_span = res.span()
            escaped = message[pos:res_span[0]]
            link = res.group()
            marked_url = GLib.markup_escape_text(link)
            result = GLib.markup_escape_text(escaped) + f"<a href=\"{marked_url}\">{marked_url}</a>"
            return result + self.parse_message(message, res_span[1])
        else:
            return GLib.markup_escape_text(message[pos:])

    def set_contents(self, data):
        if data["type"] == "empty":
            self.set_visible(False)
        else:
            self.set_visible(True)
            self.username.set_label(data["username"])

            # Use gear avatar for system messages
            if data["type"] == "system":
                self.avatar.set_text("\U00002699") # Gear emoji
            else:
                self.avatar.set_text(data["username"])

            first = True
            for message in data["text"]:
                margin = 5 if not first else 0
                first = False
                markuped = self.parse_message(message)
                msg = Gtk.Label(label=markuped, selectable=True,
                                wrap=True, wrap_mode=Pango.WrapMode.WORD_CHAR, xalign=0,
                                margin_top=margin, use_markup=True)
                self.message_list.append(msg)