require 'rexml/document'
$strings_hash = {}
$found_objtooltips = {}
$found_iitooltips = {}
$found_failtexts = {}
$found_displaytexts = {}
$found_convtexts = {}
$found_charnames = {}
$found_journals = {}
$found_casefiles = {}
$found_locations = {}
$found_maplocations = {}
$found_tutorials = {}
$found_minigamerules = {}

doc = REXML::Document.new(File.open("strings.xml"))
doc.elements.each('Workbook/Worksheet/Table/Row'){ |row|
	ctr = 0
	id = ""
	row.elements.each('Cell/Data'){ |data|
		if(ctr == 0) then
			id = data.text
		else
			$strings_hash[id] = data.text
		end
		ctr+=1
	}
}

def replaceXml(s)
	if(s.nil?) then return "" end
	p = s
	while(p.index("<"))
		p = p.sub("<","&lt;")
	end
	while(p.index(">"))
		p = p.sub(">","&gt;")
	end
	return p
end

def writeHash(out)
	keys = $strings_hash.keys.sort()
	for key in keys do
		entry = $strings_hash[key]
		entry = replaceXml(entry)
		good = true
		if(key.match('objtxt\|').to_s == "objtxt|") then
			if $found_objtooltips[key].nil? then
				good = false
			end
		elsif(key.match('invtxt\|').to_s == "invtxt|") then
			if $found_iitooltips[key].nil? then
				good = false
			end
		elsif(key.match('failtext\|').to_s == "failtext|") then
			if $found_failtexts[key].nil? then
				good = false
			end
		elsif(key.match('displaytext\|').to_s == "displaytext|") then
			if $found_displaytexts[key].nil? then
				good = false
			end
		elsif(key.match('conv\|').to_s == "conv|") then
			if $found_convtexts[key].nil? then
				good = false
			end
		elsif(key.match('charname\|').to_s == "charname|") then
			if $found_charnames[key].nil? then
				good = false
			end
		elsif(key.match('journal\|').to_s == "journal|") then
			if $found_journals[key].nil? then
				good = false
			end
		elsif(key.match('casefile\|').to_s == "casefile|") then
			if $found_casefiles[key].nil? then
				good = false
			end
		elsif(key.match('location\|').to_s == "location|") then
			if $found_locations[key].nil? then
				good = false
			end
		elsif(key.match('map\|').to_s == "map|") then
			if $found_maplocations[key].nil? then
				good = false
			end
		elsif(key.match('^tutorial\|').to_s == "tutorial|") then
			if $found_tutorials[key].nil? then
				good = false
			end
		elsif(key.match('helptutorial\|').to_s == "helptutorial|") then
			if $found_minigamerules[key].nil? then
				good = false
			end
		end
		if good then
			out.puts "   <Row>"
			out.puts "    <Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">#{key}</Data></Cell>"
			out.puts "    <Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">#{entry}</Data></Cell>"
			out.puts "   </Row>"
		end
	end
end

def writeToStrings()
	new_strings = File.open("strings_new.xml","w")
	old_strings = File.open("strings.xml","r")
	ignoreRows = false
	old_strings.each_line{|line|
		if(line.strip == "<Row>") then
			if(!ignoreRows) then
				writeHash(new_strings)
				ignoreRows = true
			else
			
			end
		else
			if(ignoreRows) then
				if(line.strip == "</Table>") then
					ignoreRows = false
					new_strings.puts(line)
				else
				
				end
			else
				new_strings.puts(line)
			end
		end
	}
	old_strings.close()
	new_strings.close()
	new_strings = File.open("strings_new.xml","r")
	old_strings = File.open("strings.xml","w")
	new_strings.each_line{|line|
		old_strings.puts(line)
	}
	old_strings.close()
	new_strings.close()
end

def readObjTooltips()
	doc = REXML::Document.new(File.open("hiddenobjects/objects.xml"))
	doc.elements.each('hiddenobjects/hiddenobject'){ |ho|
		needId = "objtxt|"+ho.attributes['tooltip'].to_s
		$strings_hash[needId] = ho.attributes['tooltip'].to_s
		$found_objtooltips[needId] = true;
	}
end

def readInvTooltips()
	doc = REXML::Document.new(File.open("inventoryitems/items.xml"))
	doc.elements.each('inventoryitems/invitem'){ |ho|
		needId = "invtxt|"+ho.attributes['tooltip'].to_s
		$strings_hash[needId] = ho.attributes['tooltip'].to_s
		$found_iitooltips[needId] = true;
	}
end

def readHotspots()
	doc = REXML::Document.new(File.open("scenes/Levels.set"))
	doc.elements.each('sceneset/scene'){|scene|
		sceneName = scene.attributes['name'].to_s
		doc2 = REXML::Document.new(File.open("scenes/#{sceneName}.scene"))
		doc2.elements.each('scene/hotspots/hotspot'){|hotspot|
			hotspotName = hotspot.elements['properties'].attributes['name']
			hotspot.elements.each('state/FailText'){|failtext|
				if(not failtext.text.nil?) then
					id = "failtext|"+sceneName+"|"+hotspotName
					$strings_hash[id] = failtext.text
					$found_failtexts[id] = true
				end
			}
			hotspot.elements.each('state/OnStartActions/function'){|func|
				if(func.attributes['type'] == "Display Text") then
					splitted = func.attributes['param'].split('^')
					myid = "displaytext|#{sceneName}|#{hotspotName}|#{splitted[0]}"
					mytext = splitted[1]
					$strings_hash[myid] = mytext
					$found_displaytexts[myid] = true
				end
			}
		}
	}
end

def readConversations()
	doc = REXML::Document.new(File.open("conversations/dia.xml"))
	doc.elements.each('conversations/conversation'){|convfile|
		convname = convfile.attributes['name']
		doc2 = REXML::Document.new(File.open("conversations/#{convname}.conv"))
		doc2.elements.each('conversation/dialog'){|dia|
			diaid = "#{convname}_none"
			dia.elements.each('meta'){|metaelem|
				diaid = metaelem.attributes['id'].to_s
			}
			diatext = ""
			dia.elements.each('text'){|textelem|
				if(not textelem.text.nil?) then
					diatext = textelem.text
				end
			}
			textid = "conv|#{convname}|#{diaid}"
			$strings_hash[textid] = diatext
			$found_convtexts[textid] = true
		}
	}
end

def readCharacterNames()
	if(File.exist?("characternames.txt")) then
		File.open("characternames.txt","r").each_line{|line|
			l = line.strip
			if(l.length() > 0 && l[0,1] != "#") then
				ls = l.split(/[\t]+/)		
				idx = "charname|"+ls[0]
				$strings_hash[idx] = ls[1]
				$found_charnames[idx] = true
			end
		}
	end
end

def readJournalEntries()
	if(File.exist?("journal.txt")) then
		File.open("journal.txt","r").each_line{|line|
			l = line.strip
			if(l.length() > 0 && l[0,1] != "#") then
				ls = l.split(/[\t]+/)		
				idx = "journal|"+ls[0]
				target = ""
				if(ls.length > 1) then
					target = ls[1]
				else
					target = ""
				end
				$strings_hash[idx] = target
				$found_journals[idx] = true
			end
		}
	end
end

def readCasefileEntries()
	if(File.exist?("casefile.txt")) then
		File.open("casefile.txt","r").each_line{|line|
			l = line.strip
			if(l.length() > 0 && l[0,1] != "#") then
				ls = l.split(/[\t]+/)		
				idx = "casefile|"+ls[0]
				target = ""
				if(ls.length > 1) then
					target = ls[1]
				else
					target = ""
				end
				$strings_hash[idx] = target
				$found_casefiles[idx] = true
			end
		}
	end
end

def readLocations()
	if(File.exist?("locations.txt")) then
		File.open("locations.txt","r").each_line{|line|
			l = line.strip
			if(l.length() > 0 && l[0,1] != "#") then
				ls = l.split(/[\t]+/)		
				idx = "location|"+ls[0]
				$strings_hash[idx] = ls[1]
				$found_locations[idx] = true
			end
		}
	end
end

def readMAPLocations()
	if(File.exist?("maplocations.txt")) then
		File.open("maplocations.txt","r").each_line{|line|
			l = line.strip
			if(l.length() > 0 && l[0,1] != "#") then
				ls = l.split(/[\t]+/)		
				idx = "map|"+ls[0]
				$strings_hash[idx] = ls[1]
				$found_maplocations[idx] = true
			end
		}
	end
end

def readTutorials()
	if(File.exist?("tutorials.txt")) then
		File.open("tutorials.txt","r").each_line{|line|
			l = line.strip
			if(l.length() > 0 && l[0,1] != "#") then
				ls = l.split(/[\t]+/)		
				idx = "tutorial|"+ls[0]
				target = ""
				if(ls.length > 1) then
					target = ls[1]
				else
					target = ""
				end
				$strings_hash[idx] = target
				$found_tutorials[idx] = true
			end
		}
	end
end

def readMinigameRules()
	doc = REXML::Document.new(File.open("minigames/minigames.xml"))
	doc.elements.each('minigames/minigame'){|mg|
		mgname = mg.attributes['codename'].to_s
		mgid = "helptutorial|#{mgname}"
		mgval = mg.attributes['rules'].to_s
		$strings_hash[mgid] = mgval
		$found_minigamerules[mgid] = true
	}
end

def writeToTextFile
	output = File.open("strings.txt","w")
	keylist = $strings_hash.keys.sort()
	for id in keylist do
		field = $strings_hash[id]
		str = "%-85s\t%s" % [id.to_s, replaceXml(field.to_s)]
		output.puts(str)
	end
	output.close()
end

readObjTooltips
readInvTooltips
puts "Finished reading tooltips..."
readHotspots
puts "Finished reading hotspots..."
readConversations
puts "Finished reading conversations..."
readCharacterNames
puts "Finished reading character names..."
readJournalEntries
puts "Finished reading journal entries..."
readCasefileEntries
puts "Finished reading casefiles..."
readLocations
puts "Finished reading locations..."
readMAPLocations
puts "Finished reading map..."
readTutorials
puts "Finished reading tutorials..."
readMinigameRules
puts "Finished reading minigame rules..."

writeToStrings
print 'press the enter key to continue...'
i = gets.to_s

print 'writing to text file'
writeToTextFile
print 'done. press enter key to continue...'
i = gets.to_s