class HStretch < Qt::Widget
  def initialize(parent = nil)
    super(parent)
     set_layout(Qt::HBoxLayout.new{add_stretch})
  end
end

class MainWindow < Qt::MainWindow

  slots :show_in_fullscreen

  def initialize(parent = nil)
    super(parent)

    set_window_icon($webkam_app.icon(:webkam))
    set_window_title($webkam_app.name + ' ' + $webkam_app.version)

    central_widget = CentralWidget.new
    set_central_widget central_widget

    @control_widget = central_widget.control_widget

    set_unified_title_and_tool_bar_on_mac true

    set_minimum_width 500
    resize(600, height)

    create_toolbar
  end

  def showEvent(event)
    WebcamVideoStream.instance.play if $dev_pool.webcam?
  end

  def show_in_fullscreen
    $fs_view.exec
  end

  def create_toolbar
    @tool_bar = (Qt::ToolBar.new do
      set_movable false
      set_tool_button_style Qt::ToolButtonTextUnderIcon
      set_icon_size Qt::Size.new(32, 32)
      toggle_view_action.set_visible false
    end)

    @action_group = Qt::ActionGroup.new(self) { set_exclusive true}

    add_tool_button('Start Page', :start, @control_widget, :show_start_page) do |action|
      action.set_checked true
    end

    add_tool_button('Take Photo', :photo, @control_widget, :show_photo_page) do |action|
      action.enabled_when_webcam_present
    end

    browse_menu = Qt::Menu.new(self) do
      @photo = add_action($webkam_app.icon(:photo_small), "Photos")
      @photo.connect(SIGNAL :triggered) do
        Qt::DesktopServices.open_url Qt::Url.new('file://' + $settings.photo_path)
      end

      connect(SIGNAL :aboutToShow) do
        @photo.set_enabled(File.exist?($settings.photo_path))
      end
    end

    browse = Qt::ToolButton.new do
      set_text "Browse"
      set_icon $webkam_app.icon(:folder)
      set_popup_mode Qt::ToolButton::InstantPopup
      set_menu browse_menu
      set_tool_button_style Qt::ToolButtonTextUnderIcon
    end


    add_tool_button('Settings', :settings, @control_widget, :show_settings_page)

    @tool_bar.add_widget browse

    @tool_bar.add_widget(HStretch.new)

    add_tool_button('Fullscreen', :fullscreen, self, :show_in_fullscreen, false) do |action|
      action.enabled_when_webcam_present
    end

    @tool_bar.add_widget(HStretch.new)

    add_tool_button('Quit', :quit, $webkam_app, :quit, false)

    add_tool_bar(@tool_bar)
  end

  def add_tool_button(text, icon, reciver, method, checkable = true)
    action = @tool_bar.add_action($webkam_app.icon(icon), text, reciver, SLOT(method))
    action.checkable =  checkable
    @action_group.add_action(action)
    
    yield action if block_given?

    return action
  end

end
