=begin
#-------------------------------------------------------------------------------------------------------------------------------------------------
#*************************************************************************************************
# Designed January 2013 by Fredo6

# Permission to use this software for any purpose and without fee is hereby granted
# Distribution of this software for commercial purpose is subject to:
#  - the expressed, written consent of the author
#  - the inclusion of the present copyright notice in all copies.

# THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#-----------------------------------------------------------------------------
# Name			:   TopoShaper_Dialogs.rb
# Original Date	:   28 Jan 13
# Description	:   TopoShaper Dialog boxes
#-------------------------------------------------------------------------------------------------------------------------------------------------
#*************************************************************************************************
=end

module F6_TopoShaper

T6[:TIT_GridDimensions] = "Grid Dimensions"
T6[:TIP_Grid_X] = "X Direction (longest)"
T6[:TIP_Grid_Y] = "Y Direction (shortest)"
T6[:TIP_Grid_Field] = "Number of cells or dimension of cell"
T6[:TIP_Grid_Length] = "Dimension of grid cells"
T6[:TIP_Grid_Linked] = "Link X and Y dimensions so that grid cells are roughly square"
T6[:MSG_Error_GridValue] = "Invalid value for Grid Dimension: %1"
T6[:MSG_Error_OutOfRange] = "Values out of range"
T6[:MSG_Warning_OutOfRange] = "Value %1 out of range. Capped at %2"

#--------------------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------------------
# Dialog box for Displaying Ruby Error
#--------------------------------------------------------------------------------------------------------------			 
#--------------------------------------------------------------------------------------------------------------			 

class GridDimensionDialog

HTML = Traductor::HTML
@@top_dialog = nil

#Invoke the Dialog box with the Exception object <e>
def GridDimensionDialog.invoke(algo, tool)
	unique_key = "Toposhaper_GridDimension_DLG"
	@@top_dialog = GridDimensionDialog.new(unique_key, algo, tool) unless Traductor::Wdlg.check_instance_displayed(unique_key)
end	

#initialization of the dialog box 
def initialize(unique_key, algo, tool)
	@algo = algo
	@tool = tool
	@unique_key = unique_key
	@in_error = nil
	
	#Creating the dialog box
	@wdlg = create_dialog_top
end

def GridDimensionDialog.close
	@@top_dialog.close_dialog_top if @@top_dialog
end

#--------------------------------------------------------------------------------------------------------------
# Dialog box configuration
#--------------------------------------------------------------------------------------------------------------			 

#Create the dialog box
def create_dialog_top
	init_dialog_top

	@wdlg = Traductor::Wdlg.new T6[:TIT_GridDimensions], @unique_key, false
	@wdlg.set_unique_key @unique_key
	@wdlg.set_size @wid_total, @hgt_total
	@wdlg.set_background_color 'lightblue'
	@wdlg.set_callback self.method('topdialog_callback') 
	@wdlg.set_on_close { on_close_top() }
	refresh_dialog_top
	@wdlg.initial_focus("ID_NX", true)
	@wdlg.show
	@wdlg
end

#Initialize parameters of the dialog box
def init_dialog_top
	@wid_extra = (RUN_ON_MAC) ? 40 : 80
	@wid_label = 50
	@wid_field = 150
	@wid_link = 30
	@wid_total = 2 * @wid_label + 2 * @wid_field + @wid_extra
	@hgt_total = 250
end

#Refresh the dialog box
def refresh_dialog_top
	@wdlg.set_html format_html_top(@wdlg)
end

#Notification of window closure
def on_close_top
	@@top_dialog = nil
	UI.start_timer(0) { @tool.notify :grid_dimension, @results }
end

#Close the dialog box
def close_dialog_top
	@results = nil
	@wdlg.close
end

#Call back for Statistics Dialog
def topdialog_callback(event, type, id, svalue)		
	case event
		
	#Command buttons
	when /onclick/i
		case id
		when 'ButtonDone'
			on_ok
		when 'ButtonCancel'
			on_cancel
		when 'IMG_LINK'
			update_linked
			@wdlg.put_focus "ID_NX", true
		end
		
	when /onKeyUp/i	#Escape and Return key
		if svalue =~ /\A27\*/
			on_cancel
		end	

	when /onfocus/i
		if @in_error 
			id_error, type = @in_error
			if type == :error && id_error != id
				@wdlg.put_focus id_error, true
			else
				color = (type == :error) ? "lightpink" : "yellow"
				@wdlg.jscript_set_prop id_error, "style.backgroundColor", color
				@in_error = nil if type == :warning
			end
		else
			color = 'white'
			@wdlg.jscript_set_prop "ID_NY", "style.backgroundColor", color
			@wdlg.jscript_set_prop "ID_NX", "style.backgroundColor", color
		end	
		
	when /onchange/i
		case id
		when "ID_NX", "ID_NY"
			svalue = check_values(svalue, id)
		end	
	end
	svalue
end

def on_cancel
	@in_error = nil
	@results = nil
	@wdlg.close
end

def on_ok
	if @in_error
		id_error, type = @in_error
		@wdlg.put_focus id_error, true
		return
	end	
	@results = { :linked => @linked, :nx => @nx, :ny => @ny }
	@wdlg.close
end

#Format a length, with special conversion for ' and " when architecture units are used
def format_length_for_html(d)
	s = Sketchup.format_length d
	s = s.gsub(/'/, '&#39;')
	s.gsub(/"/, '&quot;')
end

def check_values(svalue, id)
	@in_error = nil
	svalue_orig = svalue
	
	#Checking the value of the dimension
	iaxis = (id == "ID_NX") ? 0 : 1
	status, @nx, @ny, svalue = @algo.grid_check_dimension_as_string(iaxis, svalue, @nx, @ny, @linked)
	
	#Handling errors
	case status
	when -1
		@in_error = [id, :error]
	when 1
		@in_error = [id, :warning]
	end	
	if @in_error
		UI.beep
		if @in_error[1] == :error
			@tool.palette_set_message T6[:MSG_Error_GridValue, svalue.inspect], 'E'
		else
			@tool.palette_set_message T6[:MSG_Warning_OutOfRange, svalue_orig, svalue], 'W'
		end
	end	

	#Updating the other dimension if linked
	if @linked
		if id == "ID_NX"
			@wdlg.jscript_set_prop "ID_NY", "value", "#{@ny}"
		elsif id == "ID_NY"
			@wdlg.jscript_set_prop "ID_NX", "value", "#{@nx}"
		end
	end	

	#Updating the distance fields
	dx, dy = @algo.grid_delta @nx, @ny
	@wdlg.set_element_value "ID_SPAN_DX", '', format_length_for_html(dx)
	@wdlg.set_element_value "ID_SPAN_DY", '', format_length_for_html(dy)
	
	svalue
end
	
#Toggle the linked dialog options and update the dialog box	
def update_linked
	@linked = !@linked
	img_link = (@linked) ? @img_link_on : @img_link_off
	cmd = "document.getElementById('IMG_LINK').src = '#{img_link}' ;"
	@wdlg.execute_script cmd
end
	
#Build the HTML for Statistics Dialog
def format_html_top(wdlg)
	#Creating the HTML stream	
	html = Traductor::HTML.new
	
	#style used in the dialog box
	bgcolor = 'BG: lightblue'
	space2 = "&nbsp;&nbsp;"
	
	html.create_style 'Title', nil, 'B', 'K: navy', 'F-SZ: 14', 'text-align: center'
	html.create_style 'Delta', nil, 'F-SZ: 11', 'K: blue', 'text-align: right'
	html.create_style 'MinMax', nil, 'F-SZ: 11', 'K: darkgrey', 'text-align: right'
	html.create_style 'Label', nil, 'F-SZ: 11', 'B', 'K: blue', 'text-align: right'
	html.create_style 'Field', nil, 'F-SZ: 11', 'K: black', 'text-align: left'
	html.create_style 'Button', nil, 'F-SZ: 10'
	html.create_style 'ButtonU', 'Button', 'BG: yellow'	
	
	#Creating the title
	title = T6[:TIT_GridDimensions]
	html.body_add "<div cellspacing='0px' cellpadding='0px' class='Title'>#{title}</div>"
	
	#Getting the current grid dimensions
	@nx, @ny, @linked = @algo.grid_get_dimensions
	dx, dy = @algo.grid_delta(@nx, @ny)
	nx_min, nx_max, ny_min, ny_max = @algo.grid_max_dimensions
	dx_min, dx_max, dy_min, dy_max = @algo.grid_max_dimensions_delta
	
	#Chain link image button
	px = 40
	py = 18
	@img_link_on = Traductor::HTML.image_file Traductor::MYPLUGIN.picture_get("Img_Linked_On")
	@img_link_off = Traductor::HTML.image_file Traductor::MYPLUGIN.picture_get("Img_Linked_Off")
	@tip_link = T6[:TIP_Grid_Linked]
	img_link = (@linked) ? @img_link_on : @img_link_off
	himg_link = Traductor::HTML.format_imagelink img_link, px, py, "IMG_LINK", nil, nil, @tip_link	
	
	#Inserting the Labels and Fields
	tip_field_x = T6[:TIP_Grid_Field]
	tip_field_y = T6[:TIP_Grid_Field]
	tip_len = T6[:TIP_Grid_Length]
	label_nx = HTML.format_span("X", "", "Label", nil, T6[:TIP_Grid_X])
	field_nx = HTML.format_input("#{@nx}", '5', "ID_NX", "Field", nil, tip_field_x)
	label_ny = HTML.format_span("Y", "", "Label", nil, T6[:TIP_Grid_Y])
	field_ny = HTML.format_input("#{@ny}", '5', "ID_NY", "Field", nil, tip_field_y)
	span_dx = HTML.format_span(Sketchup.format_length(dx), "ID_SPAN_DX", "Delta", nil, tip_len)
	span_dy = HTML.format_span(Sketchup.format_length(dy), "ID_SPAN_DY", "Delta", nil, tip_len)
	span_nxmin = HTML.format_span("#{nx_min} <  ", nil, "MinMax")
	span_nxmax = HTML.format_span("< #{nx_max}", nil, "MinMax")
	span_nymin = HTML.format_span("#{ny_min} <  ", nil, "MinMax")
	span_nymax = HTML.format_span("< #{ny_max}", nil, "MinMax")
	span_dxmin = HTML.format_span("#{Sketchup.format_length(dx_max)} > ", nil, "MinMax")
	span_dxmax = HTML.format_span("  > #{Sketchup.format_length(dx_min)}", nil, "MinMax")
	span_dymin = HTML.format_span("#{Sketchup.format_length(dy_max)} > ", nil, "MinMax")
	span_dymax = HTML.format_span("  > #{Sketchup.format_length(dy_min)}", nil, "MinMax")
	text = ""
	text += "<table ID='ID_TABLE' width='99%' cellpadding='2px'><tr>"
	text += "<tr><td align='center'>#{label_nx}</td><td align='center'>#{label_ny}</td></tr>"
	text += "<tr><td align='center'>#{span_nxmin}#{field_nx}#{span_nxmax}</td>"
	text += "<td align='center'>#{span_nymin}#{field_ny}#{span_nymax}</td></tr>"
	text += "</td><td align='center'>#{span_dxmin}#{span_dx}#{span_dxmax}</td><td align='center'>#{span_dymin}#{span_dy}#{span_dymax}</td></tr>"
	text += "<tr><td colspan='2' align='center'>#{himg_link}</td></tr>"
	text += "</table>"
	html.body_add text
	
	#Creating the dialog box buttons	
	butdone = HTML.format_submit T6[:T_BUTTON_Done], id="ButtonDone", 'ButtonU', nil
	butcancel = HTML.format_button T6[:T_BUTTON_Cancel], id="ButtonCancel", 'Button', nil
	html.body_add "<table width='99%' cellpadding='6px'><tr>"
	html.body_add "<td width='50%' align='left'>", butcancel, "</td>"
	html.body_add "<td align='right'>", butdone, "</td>"
	html.body_add "</tr></table>"
		
	#Returning the HTML object
	html	
end

end	#class GridDimensionDialog

end	#End Module F6_TopoShaper
