#-----------------------------------------------------------
# WxRuby Extension (wxsugar-like)
#
# Author: Dice
# License: NYSL 0.9982 (http://www.kmonos.net/nysl/)
# Last Update: 2009-07-04 (remove instance_exec)
#-----------------------------------------------------------

require 'wx'

class Wx::Window
	def construct_children(&block)
		c = WxConstructor.new(self)
		c.instance_eval(&block)
	end
end
			
			
class WxConstructor
	attr_reader :body, :parent
	def initialize(body, parent = nil)
		@body = body
		@parent = parent
		@location_args = [0, 0, 0]
	end

	public
	def widget(cls, *args, &block)
		wid = cls.new(parent_widget, *args)
		self.class.new(wid, self).instance_eval(&block) if block
		
		case @body
		when Wx::Sizer
			@body.add(wid, *@location_args)
		end
		
		return wid
	end
	alias window widget
	
	def page(label, cls = Wx::Panel, *args, &block)
		wid = widget(cls, *args, &block)
		
		@body.add_page(wid, label)
	end
	
	def sizer(cls, *args, &block)
		sz = cls.new(*args)
		self.class.new(sz, self).instance_eval(&block) if block
		
		case @body
		when Wx::Sizer then
			@body.add(sz, *@location_args)
		else
			@body.set_sizer(sz)
		end
		
		return sz
	end
	
	def hbox_sizer(&block)
		sizer(Wx::BoxSizer, Wx::HORIZONTAL, &block)
	end
	
	def vbox_sizer(&block)
		sizer(Wx::BoxSizer, Wx::VERTICAL, &block)
	end
	
	def static_hbox_sizer(label, &block)
		box = Wx::StaticBox.new(parent_widget, :label => label)
		sizer(Wx::StaticBoxSizer, box, Wx::HORIZONTAL, &block)
	end

	def static_vbox_sizer(label, &block)
		box = Wx::StaticBox.new(parent_widget, :label => label)
		sizer(Wx::StaticBoxSizer, box, Wx::VERTICAL, &block)
	end

	
	def stretch_spacer(proportion = @location_args[0])
		@body.add_stretch_spacer(proportion)
	end

	
	private
	def locate(*args)
		if on_sizer? then
			@location_args = args
		else
			raise
		end
	end
	
	def on_sizer?
		@body.kind_of?(Wx::Sizer)
	end
	
	def proportion(v)
		@location_args[0] = v
	end
	
	def expand
		@location_args[1] |= Wx::EXPAND
	end
	
	
	def border(v)
		@location_args[1] |= Wx::ALL
		@location_args[2] = v
	end
	
	def horizontal_border(v)
		@location_args[1] |= (Wx::LEFT | Wx::RIGHT)
		@location_args[2] = v
	end
	
	def vertical_border(v)
		@location_args[1] |= (Wx::TOP | Wx::BOTTOM)
		@location_args[2] = v
	end
	
	
	def parent_widget
		cur = self
		while cur do
			if cur.body.kind_of?(Wx::Window) then
				return cur.body
			end
			cur = cur.parent
		end
		
		
		raise "parent widget not found."
	end
end
