#author: Dominic Oldrey
#version: 1.0
#history
#1.0 First release
#Notes:   This is my first plugin.  Thanks for sketchUcation and sketchup tutorials.  It's very messy but works:)

#licence: your only duty is to share any improvements and/or upgrades of this code under this same condition

#UI.messagebox("Loading Domn's Plugin!")

require 'sketchup.rb'

#SKETCHUP_CONSOLE.show

UI.menu("Tools").add_item("Extrapolate Selected Edge"){
	#UI.messagebox("Grabbing edges")
	
	if(Sketchup.active_model.selection.length == 0)
		UI.messagebox "Please select edge prior to running this script"
		#Sketchup.active_model.select_tool Select
		return
	end
	
	sel = Sketchup.active_model.selection
	
	if(sel[0].typename == "Edge")
		edge = sel[0]
		sel.clear
		
		prompts = ["Threshold"]
		defaults = [0.85]
		threshold = UI.inputbox(prompts, defaults, "Selection threshold 0 (everything) to 1 (exact)")
		
		grab_edges(edge, threshold)
	else
		UI.messagebox "Please select edge prior to running this script"
		#Sketchup.active_model.select_tool Select
		return
	end
}

def grab_edges(edge, threshold)

	edges = []
	edges.push(edge)
	
	while edges.count > 0 do
		selection_set = Sketchup.active_model.selection
		selection_set.add(edges[0])
		
	 	#get the joined edges for the edge
 	
 		numberfound = 0
 	
 		vertices = edges[0].vertices
 		vertex1 = vertices[0]
 		vertex2 = vertices[1]
 		entities = vertices[0].edges + vertices[1].edges
 	
 		entities.delete(edges[0]) 	
 	 	
 	 	newedges = []
 	 	
	 	entities.each{|e|
	 		if(selection_set.contains? e)
	 			next
	 		end
	 		if(e.typename == "Edge")
	 			test1 = vertex1.used_by? e
	 			test2 = vertex2.used_by? e
	 				
	 			if(test1 ^ test2)
	 				newedges[numberfound] = e
	 				numberfound = numberfound + 1
	 			end
			end
		}
		
	
	  	
	 	#check if the joined edges are roughly in the same direction as the current edge
	 	line = edges[0].line
	 	mainvec = line[1]
 	
 		mainvec = mainvec.normalize
 	
 	 	validedges = []
 		numberfound = 0
 	
	 	newedges.each{|e|
	 		line = e.line
	 		newvec = line[1]
	 		newvec = newvec.normalize
	 		
	 		d = mainvec.dot newvec
	 		
	 		if(d >= threshold[0])
	 			validedges[numberfound] = e
	 			numberfound = numberfound + 1
	 		end
	 	} 	
 	

 	
	 	#if so add that edge to the selection
	 	#and run grab_edges on the new edge
 	
	 	selection_set = Sketchup.active_model.selection
 	
	 	validedges.each{|e|
	 		if(selection_set.contains? e)
	 		else
	 			edges.push(e)
	 		end
	 	}
	 	
 		edges.delete(edges[0])
 		
 		end 	
end
  
