# message_row.py
#
# Copyright 2024 Christopher Talbot
#
# 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
from gi.repository import Gtk
from gi.repository import Gdk
import gettext

import gtk_meshtastic_client.utils as utils

@Gtk.Template(resource_path='/org/kop316/meshtastic/ui/message_row.ui')
class MessageRow(Gtk.ListBoxRow):
    __gtype_name__ = 'MessageRow'

    message_content = Gtk.Template.Child()
    message_body = Gtk.Template.Child()
    short_name_label = Gtk.Template.Child()
    long_name_label = Gtk.Template.Child()
    date_and_delivery_label = Gtk.Template.Child()
    content_grid = Gtk.Template.Child()
    popover = Gtk.Template.Child()

    delivered = False
    pki_encryption = False
    date = 0
    message_id = -1
    is_direct_message = False

    def update_date_pki_and_delivery_label(self):
        if self.delivered and self.is_direct_message and not self.pki_encryption:
            self.date_and_delivery_label.set_label(utils.getTimeAgoDate(self.date) + " 🔓 ✓")
        elif self.is_direct_message and not self.pki_encryption:
            self.date_and_delivery_label.set_label(utils.getTimeAgoDate(self.date) + " 🔓")
        elif self.delivered:
            self.date_and_delivery_label.set_label(utils.getTimeAgoDate(self.date) + " ✓")
        else:
            self.date_and_delivery_label.set_label(utils.getTimeAgoDate(self.date))

    def set_message_id(self, message_id):
        self.message_id = message_id

    def update_ui(self):
        self.update_date_pki_and_delivery_label()

    def update_delivery(self, delivered):
        self.delivered = delivered
        if self.delivered and self.date != 0:
            self.update_ui()

    def update_pki_encryption(self, pki_encryption):
        self.pki_encryption = pki_encryption
        if self.is_direct_message and not self.pki_encryption and self.date != 0:
            self.update_ui()

    def set_direct_message(self, is_direct_message):
        self.is_direct_message = is_direct_message
        if self.is_direct_message and not self.pki_encryption and self.date != 0:
            self.update_ui()

    def set_date(self, date):
        self.date = date
        self.update_ui()

    def set_short_name(self, short_name):
        self.short_name = short_name
        self.short_name_label.set_label(short_name)

    def set_long_name(self, long_name):
        self.long_name = long_name
        self.long_name_label.set_label(long_name)

    def set_message_content(self, message):
        self.message_content = message
        linkified_message = utils.linkifyMessage(message)

        if linkified_message == message:
            self.message_body.set_text(message)
        else:
            self.message_body.set_markup(linkified_message)

    def set_message_direction(self, direction):
        if direction == utils.MsgDirection.In.value:
            self.message_content.add_css_class ("bubble_white");
            self.message_content.set_halign (Gtk.Align.START);
            self.content_grid.set_halign (Gtk.Align.START);
            self.date_and_delivery_label.set_halign (Gtk.Align.START);
            self.long_name_label.set_halign (Gtk.Align.START);
            self.short_name_label.set_halign (Gtk.Align.START);
        elif direction == utils.MsgDirection.Out.value:
            self.message_content.add_css_class ("bubble_blue");
            self.message_content.set_halign (Gtk.Align.END);
            self.content_grid.set_halign (Gtk.Align.END);
            self.date_and_delivery_label.set_halign (Gtk.Align.END);

            """
            If it's an outgoing message, we know who it is (ourselves). No
            point in showing the authors
            """
            self.long_name_label.set_visible (False);
            self.short_name_label.set_visible (False);
        else:
            self.logger.warning("You didn't pick a correct direction!")

    def delete_message(self):
        app = Gtk.Application.get_default()
        win = Gtk.Application.get_active_window(app)
        channel_id = win.connection_page_bin.database.delete_message(self.message_id, self.date)

        channel_row = win.channels_page_bin.find_channel_by_id(channel_id)
        if not channel_row:
            channel_row = win.channels_page_bin.find_dm_by_id(channel_id)
        if channel_row:
            channel_row.nav_page.delete_msg_by_id(self.message_id)

    """self doesn't seen to work, but self is the correct widget for self"""
    def on_delete_message(self, widget, action_name, param):
        widget.delete_message()

    """self doesn't seen to work, but self is the correct widget for self"""
    def on_copy_text(self, widget, action_name, param):
        clipboard = widget.get_clipboard()
        clipboard.set(widget.message_content)

    def right_clicked_cb(self, gesture, n_press, x, y, secondary_button_gesture):
        secondary_button_gesture.set_state(Gtk.EventSequenceState.CLAIMED)
        self.popover.show()

    def long_pressed_cb(self, gesture, x, y, long_press_gesture):
        long_press_gesture.set_state(Gtk.EventSequenceState.CLAIMED)
        self.popover.show()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        app = Gtk.Application.get_default()

        self.logger = app.logger

        secondary_button_gesture = Gtk.GestureClick(button=Gdk.BUTTON_SECONDARY)
        secondary_button_gesture.connect("released", self.right_clicked_cb, secondary_button_gesture)
        self.add_controller(secondary_button_gesture)

        long_press_gesture = Gtk.GestureLongPress()
        long_press_gesture.connect("pressed", self.long_pressed_cb, long_press_gesture)
        self.add_controller(long_press_gesture)

        self.popover.set_parent(self.message_content)
        self.install_action("message_row.copy-text", None, self.on_copy_text)
        self.install_action("message_row.delete-message", None, self.on_delete_message)
