# channel_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
from enum import Enum

import gtk_meshtastic_client.utils as utils
import gtk_meshtastic_client.message_storage as message_storage

@Gtk.Template(resource_path='/org/kop316/meshtastic/ui/channel_row.ui')
class ChannelRow(Adw.ActionRow):
    __gtype_name__ = 'ChannelRow'

    channel_number_label = Gtk.Template.Child()
    unread_messages_image = Gtk.Template.Child()
    popover = Gtk.Template.Child()
    delete_chat_menu_button = Gtk.Template.Child()
    encrypted = Gtk.Template.Child()

    index = -1
    role = -1
    channel_id = "aa"
    is_dm = False
    publicKey = "MA=="

    def set_public_key(self, publicKey):
        if not publicKey:
            self.logger.warning("publickey is NULL! This is a programming Error")
            return
        elif publicKey == "":
            self.logger.warning("publickey is empty! This is a programming Error")
            return
        self.publicKey = publicKey

        if self.publicKey != "MA==":
            self.encrypted.set_visible(True)
        else:
            self.encrypted.set_visible(False)

    def set_index(self, index):
        self.index = index
        self.channel_number_label.set_label(str(index))

    # Index: What channel it is on (0-7)
    # Role: Disabled (0), Primary (1) or secondary (2)
    # PSK: AES key
    # Name: Name

    def set_nav_page(self, nav_page):
        self.nav_page = nav_page

    def set_role(self, role):
        self.role = role
        self.set_subtitle("Role: " + str(utils.ChannelRole(role).name))

    def set_channel_id(self, title, psk_base64):
        if not title and psk_base64 == "AQ==":
            title = "LongFast"
        elif title == "" and psk_base64 == "AQ==":
            title = "LongFast"

        if psk_base64 != "MA==" and psk_base64 != "AQ==":
            self.encrypted.set_visible(True)
        else:
            self.encrypted.set_visible(False)

        self.channel_id = message_storage.create_channel_id(title, psk_base64)

    def set_dm_id(self, id):
        self.channel_id = id
        self.dm = True
        self.delete_chat_menu_button.set_visible(True)

    def set_channel_title(self, title, psk_base64):
        if not title and psk_base64 == "AQ==":
            self.title = "LongFast"
        elif not title:
            self.title = "LongFast"
        else:
            self.title = title

        self.set_title(self.title)

    def clear_history(self):
        app = Gtk.Application.get_default()
        win = Gtk.Application.get_active_window(app)
        win.connection_page_bin.database.clear_history(self.channel_id)
        self.nav_page.clear_message_list()

    def delete_chat(self):
        app = Gtk.Application.get_default()
        win = Gtk.Application.get_active_window(app)
        self.clear_history()
        win.connection_page_bin.database.delete_dm(self.channel_id)
        win.channels_page_bin.remove_dm_row(self.channel_id)

    def _delete_chat_dialog_callback(self, dialog, response, user):
        if "continue" != response:
            return

        self.delete_chat()

    def _clear_history_dialog_callback(self, dialog, response, user):
        if "continue" != response:
            return

        self.clear_history()

    def delete_chat_dialog(self):
        app = Gtk.Application.get_default()
        win = Gtk.Application.get_active_window(app)
        dialog = Adw.AlertDialog.new(_("Alert"),
                                     _("This will delete this chat. Continue?"))
        dialog.add_response ("close",  _("_Close"))
        dialog.add_response ("continue",  _("_Continue"))

        dialog.set_response_appearance ("continue",
                                        Adw.ResponseAppearance.DESTRUCTIVE)

        dialog.connect("response", self._delete_chat_dialog_callback, self)

        dialog.present (win)

    def clear_history_dialog(self):
        app = Gtk.Application.get_default()
        win = Gtk.Application.get_active_window(app)
        dialog = Adw.AlertDialog.new(_("Alert"),
                                     _("This will delete all of your history. Continue?"))
        dialog.add_response ("close",  _("_Close"))
        dialog.add_response ("continue",  _("_Continue"))

        dialog.set_response_appearance ("continue",
                                        Adw.ResponseAppearance.DESTRUCTIVE)

        dialog.connect("response", self._clear_history_dialog_callback, self)

        dialog.present (win)

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

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

    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()

        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.channel_number_label)

        self.install_action("message_row.clear-history", None, self.on_clear_history)
        self.install_action("message_row.delete-chat", None, self.on_delete_chat)
        self.logger = app.logger
