# position_telemetry_dialog.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 Gio
import gettext
import meshtastic.mesh_interface
import meshtastic
import os
import base64

import gtk_meshtastic_client.connection_page
import gtk_meshtastic_client.utils as utils

@Gtk.Template(resource_path='/org/kop316/meshtastic/ui/position_telemetry_dialog.ui')
class PositionTelemetryDialog(Adw.Dialog):
    __gtype_name__ = 'PositionTelemetryDialog'

    channel_selection = Gtk.Template.Child()

    def _send_position_or_telemetry_finish(self, self_object, result: Gio.AsyncResult):
        app = Gtk.Application.get_default()
        win = Gtk.Application.get_active_window(app)
        position = self_object.position

        if not Gio.Task.is_valid(result, self_object):
            self.logger.warning("Not valid GTask")
            return

        success = result.propagate_boolean()
        if not success:
            self.logger.warning("Position Request failed!")
            return

    def _send_position_or_telemetry_async(self, callback) -> None:
        def _send_position_or_telemetry(task, _source_object, _task_data, _cancellable):
            app = Gtk.Application.get_default()
            win = Gtk.Application.get_active_window(app)

            interface = win.connection_page_bin.interface
            channel_index = _source_object.channel_selection.get_selected()
            dest_id = _source_object.dest_id
            position = _source_object.position

            _source_object.close()

            if self.position:
                try:
                    interface.sendPosition(destinationId=dest_id, wantResponse=True, channelIndex=channel_index)
                    win.window_toast_overlay.add_toast(Adw.Toast(title="Could not request position"))
                except:
                    task.return_boolean(False)
                    return
                else:
                    task.return_boolean(True)
                    win.window_toast_overlay.add_toast(Adw.Toast(title="Received new position"))
                    return
            else:
                try:
                    interface.sendTelemetry(destinationId=dest_id, wantResponse=True, channelIndex=channel_index)
                except:
                    task.return_boolean(False)
                    win.window_toast_overlay.add_toast(Adw.Toast(title="Could not request telemetry"))
                    return
                else:
                    task.return_boolean(True)
                    win.window_toast_overlay.add_toast(Adw.Toast(title="Received telemetry"))
                    return

        task = Gio.Task.new(self, None, callback)
        task.run_in_thread(_send_position_or_telemetry)

    @Gtk.Template.Callback()
    def _set_channel_clicked_cb(self, button):
        self._send_position_or_telemetry_async(callback=self._send_position_or_telemetry_finish)

    def set_dialog_title(self, title):
        self.set_title(title)

    def set_dest_id(self, dest_id):
        self.dest_id = dest_id

    def set_position_or_telemetry(self, position):
        self.position = position

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

        self.logger = app.logger
