#
#  Copyright (c) 2022 Canonical Ltd.
#
#  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 2 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, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA

import os
from gettext import gettext as _

from softwareproperties.gtk.utils import setup_ui
import softwareproperties.gtk.dialogs as dialogs

class DialogUaDetach:
    def __init__(self, parent, datadir, ua_object):
        """setup up the gtk dialog"""
        setup_ui(self, os.path.join(datadir, "gtkbuilder", "dialog-ua-detach.ui"), domain="software-properties")

        self.ua_object = ua_object
        self.dialog = self.dialog_ua_detach
        self.dialog.set_transient_for(parent)

        self.detaching = False

        # GTK4: Manually connect signals.
        self.button_cancel.connect('clicked', self.on_cancel_clicked)
        self.button_detach.connect('clicked', self.on_detach_clicked)

    def present(self):
        self.dialog.present()

    def update_state(self):
        self.button_detach.set_sensitive(not self.detaching)

    def on_detach_clicked(self, button):
        if self.detaching:
            return

        self.detaching = True
        def on_reply():
            self.dialog.hide()
        def on_error(error):
            # Only pop-up an error dialog if something other than the
            # user clicking "Cancel" on the auth dialog happens.
            if error and error.get_dbus_name() != 'com.canonical.UbuntuAdvantage.AuthFailed':
                dialogs.show_error_dialog(
                self.dialog,
                _("Failed to detach Ubuntu Pro"),
                error.get_dbus_message(),
            )
            self.detaching = False
            self.update_state()
        self.ua_object.Detach(reply_handler=on_reply, error_handler=on_error, dbus_interface='com.canonical.UbuntuAdvantage.Manager', timeout=600)
        self.update_state()

    def on_cancel_clicked(self, button):
        self.dialog.hide()
