from gi.repository import Gtk, Adw

class FlagRow(Adw.ActionRow):
    __gtype_name__ = 'FlagRow'

    def __init__(self, flag_data):
        super().__init__()
        self.flag = flag_data['flag']

        self.flag_name = flag_data['name']
        self.set_title(self.flag_name)

        self.flag_description = flag_data['description']
        self.set_subtitle(self.flag_description)

        self.set_selectable(False)
        self.set_activatable(True)

        self.switch = Gtk.Switch(
            halign=Gtk.Align.CENTER,
            valign=Gtk.Align.CENTER
        )
        self.add_suffix(self.switch)

        self.connect("activated", lambda _: self.switch.activate())

    def get_active(self):
        return self.switch.get_active()

@Gtk.Template(resource_path='/ru/eepm/PlayGUI/widgets/flagsdialog.ui')
class FlagsDialog(Adw.Dialog):
    __gtype_name__ = 'FlagsDialog'
    main_listbox = Gtk.Template.Child()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.rows = []

    def apply_flags(self, tool, full_command, ignored_flags=None):
        # Debug: Print initial command and tool
        print(f"Initial command: {full_command}")
        print(f"Tool: {tool}")

        for row in self.rows:
            # Debug: Print each flag's active state
            print(f"Checking flag {row.flag}: {row.get_active()}")

            if row.get_active():
                if ignored_flags is None or row.flag not in ignored_flags:
                    # Debug: Print flag to be applied
                    print(f"Applying flag: {row.flag}")
                    # Append flag to the command
                    full_command = full_command.replace(tool, f"{tool} {row.flag}")

        # Debug: Print the final command after applying flags
        print(f"Final command: {full_command}")

        return full_command

    def add_flags(self, flags):
        for flag_data in flags:
            if not isinstance(flag_data, dict) or not all(key in flag_data for key in ['flag', 'name', 'description']):
                raise ValueError("Each flag must be a dictionary with 'flag', 'name', and 'description' keys")

            row = FlagRow(flag_data)

            self.rows.append(row)

            self.update_listbox()

    def remove_flag_row(self, flag):
        self.rows = [row for row in self.rows if row.flag != flag]

        self.update_listbox()

    def update_listbox(self):
        self.main_listbox.remove_all()
        for row in self.rows:
            self.main_listbox.append(row)

    def clear(self):
        self.main_listbox.remove_all()
        self.rows.clear()