Shoes.app :title => "Paint", :width => 800, :height => 600 do
  MAIN_MENU_HEIGHT = 50
  @tools = [:Tools, :rect, :oval, :line]
  @undo_pile = []
  
  # Layout of the tools
  def draw_tools 
    @toolbox = flow do
      border "#aaaaaa", :strokewidth => 5     
      flow :margin => 5 do             
        stack :width => "100%",:height => MAIN_MENU_HEIGHT-10 do
          # Main horizontal menu
          background "#cccccc"
          flow do
            list_box :items => @tools,:margin => 5, :width => 100,:choose => :Tools do |list|
              @shape_type = list.text.to_sym
            end
		        button("Show/Hide Options", :width => 150, :margin => 5) do
		          @options.toggle
		        end      
            button("Undo Last", :margin => 5,:width => 100) do
              @undo_pile.pop.remove
            end
            button("Clear", :margin => 5,:width => 100) do
              @toolbox.parent.clear
              draw_tools
            end
          end
        end
        @options = stack :width => "100%" do
          # Horizontal options menu
          background "#eeeeee"
          flow do
            button("Fill Color", :margin => 5,:width => 100) do
	            fill ask_color("Pick a Color")
            end
	          button("Stroke Color", :margin => 5,:width => 100) do
	            stroke ask_color("Pick a Color")
            end
            stroke_width = edit_line :width => 50,:margin => 5
            button("<-- Set Line Width", :width => 150, :margin => 5) do
              strokewidth stroke_width.text.to_i
            end
          end          
        end
        @options.hide
      end
    end
  end
  
  draw_tools
  
  # Drawing Events  
  click do |b,x,y|
    @options.hide
    if y > MAIN_MENU_HEIGHT
      if @shape_type == :line
        @shape = send(@shape_type,x,y,x,y)
        draw_line(x,y)
      else
        @shape = send(@shape_type,x,y,1,1)
        draw_boxed(x,y)
      end
    end
  end
  
  release do
    @undo_pile << @shape
    if @undo_pile.length > 10
      @undo_pile.shift
    end
    motion nil
  end
  
  # Drawing Methods
  def draw_line(ex,wye)
    motion do |x,y|
      @shape.remove
      @shape = send(@shape_type,ex,wye,x,y)
    end
  end
  
  def draw_boxed(ex,wye)
    motion do |x,y|
      if y > MAIN_MENU_HEIGHT
        if x > ex and y > wye
          @shape.style(:width => x-ex,:height => y-wye)    
        elsif x < ex and y > wye
          @shape.style(:left => x,:width => ex-x,:height => y-wye)
        elsif x < ex and y < wye
          @shape.style(:left => x,:top => y,:width => ex-x,:height => wye-y)        
        elsif x > ex and y < wye
          @shape.style(:top => y,:width => x-ex,:height => wye-y)
        end
      end
    end
  end
end
