# Supports Organizer.rb
=begin rdoc

= weld.rb
Copyright 2004-2013 by Rick Wilson - All Rights Reserved

== Disclaimer
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.

== License
This software is distributed under the Smustard End User License Agreement
http://www.smustard.com/eula

== Information
Author:: Rick Wilson
Organization:: Smustard
Name:: ViewSaver
Version:: 1.0.0
SU Version:: 4.0
Date:: 2014-04-25
Description:: Save and restore views (camera positions) in a WebDialog

Usage::
* 1:: Install into the plugins directory or into the Plugins/examples directory and manually load from the ruby console "load 'examples/weld.rb'" 
* 2:: Activate the plugin (View>ViewSaver)
* 3:: WebDialog will appear with any saved views and icon to add new views or modify existing views
	
History::
* 1.0.0:: 2014-04-25
	* first version

ToDoList::
	* 
	* 

=end



module Smustard
	
	if ($submenu) # legacy programs creating a global
		Smustard::Submenu = $submenu unless Smustard.constants.include?("Submenu")
	else
		Smustard::Submenu = nil unless Smustard.constants.include?("Submenu")
	end
	
	if ($smustard_toolbar)	# legacy programs creating a global
		Smustard::Toolbar = $smustard_toolbar unless Smustard.constants.include?("Toolbar")
	else
		Smustard::Toolbar = UI::Toolbar.new("Smustard") unless Smustard.constants.include?("Toolbar")
	end



class ViewSaverAppObserver < Sketchup::AppObserver

	def onNewModel(a,b=0)
		Smustard::ViewSaver.update_ad()
		Smustard::ViewSaver.create_dialog()
	end

	def onOpenModel(a,b=0)
		Smustard::ViewSaver.update_ad()
		Smustard::ViewSaver.create_dialog()
	end

end #class ViewSaverAppsObserver



class ViewSaverModelObserver < Sketchup::ModelObserver
	
	def onTransactionUndo(model)
		Smustard::ViewSaver.create_dialog()
	end

	def onTransactionRedo(model)
		Smustard::ViewSaver.create_dialog()
	end
	
end #class ViewSaverModelObserver



class ViewSaver

	@@model = nil
	@@attdict = nil
	@@instance = nil
	@@path = File.dirname(__FILE__)
	@@app_observer ||= Sketchup.add_observer(Smustard::ViewSaverAppObserver.new())
	@@model_observer ||= Sketchup.active_model.add_observer(Smustard::ViewSaverModelObserver.new())
	
	@@cmd_view_saver = UI::Command.new("View Saver"){ Smustard::ViewSaver.new() }
	@@cmd_view_saver.tooltip = "ViewSaver"
	@@cmd_view_saver.tooltip = "Save camera views in model"
	@@cmd_view_saver.large_icon = "ViewSaverLarge.png"
	@@cmd_view_saver.small_icon = "ViewSaverSmall.png"

	
	@@header = <<SmustardViewSaverHTML
<!doctype html>

<html>
<head>
<title>Smustard View Saver</title>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<style>

html,body {
	font-family: Arial, Calibri, Helvetica, Tahoma, Verdana, Sans Serif;
	font-size: 10pt;
}

.view {
	cursor: pointer;
	height: 16px;
	padding: 3px;
}

.view2 {
	cursor: pointer;
	height: 16px;
	padding: 3px;
	background-color: #fbfbfb;
}

.activate {
	float: left;
}

.addview {
	width: 56px;
	padding: 6px;
	border: 1px solid #ddd;
	border-radius: 6px;
	box-shadow: 3px 3px 8px #ddd;
}

.del {
	width: 14px;
	height: 14px;
	cursor: pointer;
	padding: 1pt;
	/*color: white;
	font-weight: bold;
	background-color: crimson;
	border-radius: 6px;*/
	float: right;
	text-align: center;
	vertical-align: middle;
	/*box-shadow: 2px 2px 6px #bbb;*/
	margin-top: -16px;
}

</style>

<script>

function activate_view(view) {
	console.log(view);
	alert(view);
	window.location = "skp:activate_view@"+view;
}

function delete_view(view) {
	console.log(view);
	alert(view);
	window.location = "skp:delete_view@"+view;
}

function add_view() {
	console.log("add view");
	alert("add view");
	window.location = "skp:add_view@";
}

</script>
</head>
<body>
SmustardViewSaverHTML
	@@footer = <<SmustardViewSaverHTML
<br>
<div class="addview" id="add_view" onclick="window.location='skp:add_view@';">Add view</div>
</body>
</html>
SmustardViewSaverHTML


	attr_accessor :dialog

	def initialize
		
		@@instance = self
		@@model = Sketchup.active_model
		@view = @@model.active_view
		@camera = @view.camera
		@dialog = nil
#		@dicts = Sketchup.active_model.attribute_dictionaries
#		if  @dicts == nil || (not @dicts["SmustardViewSaver"])
#			Sketchup.active_model.set_attribute("SmustardViewSaver","View001",camera_array(@camera))
#			@dicts = Sketchup.active_model.attribute_dictionaries
#			@dicts["SmustardViewSaver"].delete_key("View001")
#		end
#		@viewsaver = @dicts["SmustardViewSaver"]
#		@@attdict = @viewsaver
#		@items = @viewsaver.length
		@html = ""
		create_dialog()
	end
	
	
	
	def camera_array(camera=@view.camera)
		values = [camera.eye,camera.target,camera.up,camera.perspective?]
		if camera.perspective?
			values.concat([camera.fov,camera.aspect_ratio,camera.focal_length,camera.image_width])
		else
			values.concat([nil,camera.aspect_ratio,nil,nil])
		end
		return  values
	end
	
	
	
	def add_view(name="View")
		#puts "add_view(#{name})"
		return nil unless name.kind_of?(String)
		@@attdict = nil unless Sketchup.active_model.attribute_dictionaries && @@attdict && @@attdict == Sketchup.active_model.attribute_dictionaries["SmustardViewSaver"]
		
		if name=="View"
			
			q = 1
			if @@attdict
				@@attdict.keys.sort.each do |key|
					if key.include?(name)
						if (k = key.gsub(name,'').to_i) >= q
							q = k+1
						end
					end
				end
			else
				
			end
			
			if q < 10
				name += "00" + q.to_s
			elsif q < 100
				name += "0" + q.to_s
			else
				name += q.to_s
			end
			#puts "name=#{name}"
			
		end	#	compare supplied name against existing names - reject duplicates unless approved
		#if Sketchup.active_model.attribute_dictionaries && @@attdict && @@attdict == Sketchup.active_model.attribute_dictionaries["SmustardViewSaver"]
		if @@attdict
			if @@attdict.keys.include?(name)
				return nil unless UI.messagebox("Do you really want to override view #{name}?",MB_YESNO)==6
				@@attdict[name] = camera_array()
				return true
			end
		
		end
		
		#puts "ready to save view #{name}"
		
		Sketchup.active_model.set_attribute("SmustardViewSaver",name,camera_array(@camera))
		@@attdict ||= Sketchup.active_model.attribute_dictionaries["SmustardViewSaver"]
		create_dialog(true)
	
	end	
	
	
	
	def delete_view(view)
		
		return nil unless view.kind_of?(String)
		return nil unless UI.messagebox("Do you really want to delete view #{view}?",MB_YESNO)==6
		return nil unless Sketchup.active_model.attribute_dictionaries && @@attdict == Sketchup.active_model.attribute_dictionaries["SmustardViewSaver"]
		@@attdict.delete_key(view)
		create_dialog(true)
		
	end
	
	
	
	def rename_view(view,name="Camera")
		
		
		
		
	end
	
	
	
	def activate_view(view)
		return nil unless view.kind_of?(String)
		return nil unless Sketchup.active_model.attribute_dictionaries && @@attdict == Sketchup.active_model.attribute_dictionaries["SmustardViewSaver"]
		#begin
			eye,target,up,pers,fov,ar,fl,iw = @@attdict[view]
			if pers
				cam1 = Sketchup::Camera.new(eye,target,up,pers,fov)
				cam1.aspect_ratio = ar
				cam1.focal_length = fl
				cam1.image_width = iw
			else
				cam1 = Sketchup::Camera.new(eye,target,up,pers)
				cam1.aspect_ratio = ar
			end
			Sketchup.active_model.active_view.camera = cam1
		#rescue
		#	puts "Can't create view: view name #{view} not found"
		#end
	end	
	
	
	
	def sort_filter_views(type,value,method="sort")
		
		
		
		
	end
	
	
	
	def make_a_scene(view)
		
		
		
		
	end
	
	
	
	def export()
		
		
		
	end
	
	
	
	def import()
		
		
		
	end
	
	
	
	def create_html()
		
		@viewlist = ""
		j = 0;
		if Sketchup.active_model.attribute_dictionaries && Sketchup.active_model.attribute_dictionaries["SmustardViewSaver"]
			@@attdict = Sketchup.active_model.attribute_dictionaries["SmustardViewSaver"]
			@@attdict.keys.each do |key|
				j = (j-1).abs;
				divclass = ((j==1) ? ("view2") : ("view"))
				@viewlist += "<div class=\"#{divclass}\"><div id=\"#{key}\" onclick=\"window.location='skp:activate_view@#{key}';\">#{key}</div><div class=\"del\" onclick=\"window.location='skp:delete_view@#{key}';\"><img src=\"#{@@path+"/delete.png"}\"></div></div>\n"
			end
		end
		@html = @@header + @viewlist + @@footer
		
		
	end
	
	
	
	def create_dialog(exists=false)
		create_html()
		#@dialog.close if exists
		@dialog = UI::WebDialog.new("Smustard View Saver") unless exists
		@dialog.set_html(@html)
		@dialog.show
		@dialog.add_action_callback("add_view") { |d,p| add_view() }
		@dialog.add_action_callback("delete_view") { |d,p| delete_view(p) }
		@dialog.add_action_callback("activate_view") { |d,p| activate_view(p) }
	end
	
	
	
	def ViewSaver.build_ui()
		Smustard::Submenu ? (organizer = Smustard::Submenu) : (organizer = UI.menu("View"))
		organizer.add_item(@@cmd_view_saver)
		Smustard::Toolbar.add_item(@@cmd_view_saver)
	end
	
	
	
	def ViewSaver.create_dialog()
		@@instance.create_dialog(true) if @@instance
	end
	
	
	
	def ViewSaver.update_ad()
		@@model_observer = Sketchup.active_model.add_observer(Smustard::ViewSaverModelObserver.new())
		@@attdict = nil
	end



end #class ViewSaver
	
	

end #module Smustard



unless file_loaded?(__FILE__)
	file_loaded(__FILE__)
	Smustard::ViewSaver.build_ui
end
