gem 'fxruby'
require 'fox16'
include Fox

module CWrp
  class MainWindow < FXMainWindow
    WIDTH = 800
    HEIGHT = 600
    PROGRESS_LABEL_WIDTH = 200

    attr_reader :image

    # Canvas to show the image as it is generated.
    class Canvas < FXCanvas
      # +container+:: Window to place canvas into.
      # +size+:: Size of image to show, in pixels (width and height).
      # +image+:: Image to display in the canvas.
      def initialize(container, size, image)
        @image = image
        super(container, :opts => LAYOUT_FIX_WIDTH|LAYOUT_FIX_HEIGHT,
          :width => size, :height => size)

        self.connect(SEL_PAINT) do |sender, sel, event|
          FXDCWindow.new(sender, event) do |dc|
           dc.drawImage(@image, 0, 0)
          end
        end
      end
    end

    # +app+:: FXRuby application.
    # +size+:: Size of image to generate, in pixels (width and height).
    def initialize(app)
      super(app, 'Roller', :opts => DECOR_ALL, :width => WIDTH)

      @current_progress_stage = 0 # Progress counter, for multiple progress items.

      main_packer = FXVerticalFrame.new(self, :opts => LAYOUT_FILL_X|LAYOUT_FILL_Y)

      # Progress bar.
      @progress_packer = FXHorizontalFrame.new(main_packer, :opts => LAYOUT_FILL_X)
      @progress_title = FXLabel.new(@progress_packer, '',
        :opts => LAYOUT_FIX_WIDTH|JUSTIFY_LEFT, :width => PROGRESS_LABEL_WIDTH)
      @progress = FXProgressBar.new(@progress_packer,
        :opts => PROGRESSBAR_NORMAL|PROGRESSBAR_HORIZONTAL|LAYOUT_FILL_X|LAYOUT_FILL_Y)
      @progress.showNumber

      # Canvas to show the image as it is drawn.
#      scroll_window = FXScrollWindow.new(main_packer,
#        :opts => LAYOUT_FILL_X|LAYOUT_FILL_Y|HSCROLLER_ALWAYS|VSCROLLER_ALWAYS)
#      scroll_packer = FXPacker.new(scroll_window,
#        :opts => LAYOUT_FILL_X|LAYOUT_FILL_Y)

#      @canvas = Canvas.new(scroll_packer, size, @image)
    end

    public
    def create
      super
      show(PLACEMENT_SCREEN)
    end

    # Moves progress bar along by a single step.
    public
    def increment_progress
      @progress.increment 1
    end

    # Resets progress bar ready for another item.
    # +title+:: Title for the progress bar.
    # +total+:: Total value to count to in the progress meter.
    public
    def reset_progress(title, total)
      @current_progress_stage += 1
      @progress_title.text = "#{title} (#{@current_progress_stage})"
      @progress.total = total
      @progress.progress = 0
    end

    # +size+:: Size of image to generate, in pixels (width and height).
    public
    def create_mask(size)
      @image = FXPNGImage.new(app, :width => size, :height => size)
      @image.create
    end

    public
    def save_mask(filename)
      @image.restore
      FXFileStream.open(filename, FXStreamSave) do |stream|
        @image.savePixels(stream)
      end
    end
  end
end
