# frozen_string_literal: true

module Plugin::SettingsGtk; end

require_relative 'menu'

Plugin.create :settings_gtk do
  on_open_setting do
    setting_window.show_all
  end

  def setting_window
    return @window if defined?(@window) && @window

    @window = window = Gtk::Window.new(_('設定'))
    window.set_size_request(320, 240)
    window.set_default_size(768, 480)
    window.icon = Skin[:settings].load_pixbuf(width: 256, height: 256) do |pb|
      window.icon = pb unless window.destroyed?
    end

    menu_switch_delegate = Struct.new(:add, :clear).new

    window.add(
      Gtk::Paned.new(:horizontal)
        .add1(gen_scrolled_menu(menu_switch_delegate))
        .add2(gen_scrolled(menu_switch_delegate))
    )

    window.ssc(:destroy) do
      @window = nil
      false
    end

    window
  end

  def gen_settings(menu_switch_delegate)
    Gtk::Grid.new.tap do |settings|
      menu_switch_delegate.add = ->(widget) do
        settings.add(widget).show_all
      end
      menu_switch_delegate.clear = -> do
        settings.hide
        settings.children.each do |child|
          settings.remove(child)
          child.destroy
        end
      end
    end
  end

  def gen_scrolled(menu_switch_delegate)
    Gtk::ScrolledWindow.new.tap do |scrolled|
      scrolled.set_policy(:never, :automatic)
      scrolled.overlay_scrolling = false
      scrolled.add_with_viewport(gen_settings(menu_switch_delegate))
    end
  end

  def gen_scrolled_menu(menu_switch_delegate)
    Gtk::ScrolledWindow.new.tap do |scrolled_menu|
      scrolled_menu.set_policy(:never, :automatic)
      scrolled_menu.overlay_scrolling = false
      scrolled_menu.add_with_viewport(gen_menu(menu_switch_delegate))
    end
  end

  def gen_menu(menu_switch_delegate)
    Plugin::SettingsGtk::Menu.new.tap do |menu|
      menu.ssc(:cursor_changed) do
        if menu.selection.selected
          active_iter = menu.selection.selected
          if active_iter
            menu_switch_delegate.clear&.()
            menu_switch_delegate.add&.(active_iter[Plugin::SettingsGtk::Menu::COL_RECORD].widget)
          end
        end
        false
      end
    end
  end
end
