# frozen_string_literal: true

class Plugin::ExtractGtk::DatasourceSelectBox < Gtk::HierarchycalSelectBox
  def initialize(sources, &)
    super(datasources, sources, &)
  end

  def datasources
    (Plugin.filtering(:extract_datasources, {}) || [{}]).first.map do |id, source_name|
      [id, source_name.is_a?(String) ? source_name.split('/') : source_name]
    end
  end

  def menu_pop(widget, _event)
    datasource = selected_datasource_names.first
    if datasource
      contextmenu = Gtk::ContextMenu.new
      contextmenu.register(Plugin[:extract]._('データソース slugをコピー'), &copy_slug(datasource))
      contextmenu.register(Plugin[:extract]._('subscriberをコピー'), &copy_subscriber(datasource))
      contextmenu.popup(widget, widget)
    end
  end

  def copy_slug(datasource)
    ->(_optional=nil, _widget=nil) do
      Gtk::Clipboard.copy(datasource.to_s)
    end
  end

  def copy_subscriber(datasource)
    ->(_optional=nil, _widget=nil) do
      Gtk::Clipboard.copy(<<~CODE % { ds: datasource.to_sym.inspect })
        subscribe(:extract_receive_message, %{ds}).each do |message|
        #{'  '}
        end
      CODE
    end
  end

  private

  def selected_datasource_names
    selection.to_enum(:selected_each).map do |_, _, iter|
      iter[ITER_ID]
    end
  end
end
