require 'rexml/document'
require 'date'
"""
	What this program does is read the current strings.xml, and update the entries related to the dialogs (either add new node, or replace the text of old node)
"""
strings = File.open("strings.xml","r")

$string_hash = {}
$found = {}
$dialogs = {}
lines = []
ids = []
idxs = []

isId = false
idName = ""

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

inTable = false
isId = false
idTemp = ""
strings.each_line{ |line|
	if(not inTable) then
		lines.push(line.chomp)
		if(line.match("<Column ss:Width=\"699.7608\" />")) then
			inTable = true
		end
	else
		if(line.match("</Table>")) then
			inTable = false
			lines.push(line.chomp)
		else
			if(line.match(">.*<")) then
				mytext = line.match(">.*<")[0]
				mytext = mytext[1,mytext.length()-2]
				if(isId) then
					$string_hash[idTemp] = mytext
					if(idTemp.match("conv\\|")) then
						#puts idTemp
						$dialogs[idTemp] = ""
					end
					isId = false
				else
					idTemp = mytext
					isId = true
				end
			end
		end
	end
}
strings.close
$found_task = {}
if(File.exist?("tasks.txt")) then
	objDialogs = File.open("tasks.txt","r")

	curTaskScene = ""
	curTaskIdx = 0
	curTaskList = ""
	totalTasks = ""
	objDialogs.each_line{ |line|
		l = line.strip
		if(l.length() > 0 && l[0,1] != "#") then
			ls = l.split(/[\t]+/)
			#puts ls
			if(ls[0].match("Task:")) then
				if(curTaskScene != "") then
					$string_hash["tasks|"+curTaskScene] = curTaskList
				end
				curTaskScene = ls[1]
				totalTasks += curTaskScene+"|"
				curTaskIdx = 0
				curTaskList = ""
			else
				idx = "task|#{curTaskScene}|"+ls[0]
				$string_hash[idx] = ls[1]
				$found_task[idx] = true
				curTaskList += ls[0]+"|"
				curTaskIdx+=1
			end
		end
	}
	if(curTaskScene != "") then
		$string_hash["tasks|"+curTaskScene] = curTaskList
	end
	$string_hash["totalmaintasks"] = totalTasks

	objDialogs.close
end
$found_loc = {}
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]+".scene"
			$string_hash[idx] = ls[1]
			$found_loc[idx] = true
		end
	}
end
$found_journ = {}
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]
			$string_hash[idx] = ls[1]
			$found_journ[idx] = true
		end
	}
end
$found_tut = {}
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 = "tut|"+ls[0]
			$string_hash[idx] = ls[1]
			$found_tut[idx] = true
		end
	}
end
$found_cut = {}
if(File.exist? "cutscenes.txt") then
	File.open("cutscenes.txt","r").each_line{|line|
		l = line.strip
		if(l.length() > 0 && l[0,1] != "#") then
			ls = l.split(/[\t]+/)		
			idx = "FLASH_"+ls[0]
			$string_hash[idx] = ls[1]
			$found_cut[idx] = true
		end
	}
end
$new_strings = File.open("strings.xml","w")

def writeConv(file)
	if(file.match('conv')) then
		doc = REXML::Document.new(File.open("dialogs/"+file))
		texts = []
		ids = []
		ctr = 0
		p = file
		p = p.sub(".conv","")
		#puts "HAHA"+file
		doc.elements.each('conversation/dialog'){|dia|
			dia.elements.each('character/reactions/itemreact'){ |ir|
				#puts ir
				ids.push("conv|"+p+"|"+ctr.to_s+"|"+ir.elements['item'].attributes.get_attribute("name").to_s)
				texts.push(replaceXml(ir.elements['text'].text))
			}
			dia.elements.each('reactions/itemreact'){ |ir|
				if(ir.elements['text'].text.nil? or ir.elements['text'].text.empty?) then
				
				else
					ids.push("conv|"+p+"|"+ctr.to_s+"|"+ir.elements['item'].attributes.get_attribute("name").to_s)
					texts.push(replaceXml(ir.elements['text'].text))
				end
			}
			dia.elements.each('text'){|t|
				ids.push("conv|#{p}|"+ctr.to_s)
				texts.push(replaceXml(t.text))
			}
			ctr+=1
		}
		i = 0
		while(i < texts.length())
			$string_hash[ids[i]] = texts[i]
			$found[ids[i]] = ""
			$dialogs[ids[i]] = ""
			i+=1
		end
	end
end

def writeHash()
	sortedKeys = $string_hash.keys.sort()
	for id in sortedKeys do
		txt = $string_hash[id]
		if($dialogs[id] != nil) then
			if($found[id] != nil) then
				$new_strings.puts("            <Row ss:Height=\"13.4064\">")
				$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
				$new_strings.puts("                    <Data ss:Type=\"String\">#{id}</Data>");
				$new_strings.puts("                </Cell>")
				$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
				$new_strings.puts("                    <Data ss:Type=\"String\">#{txt}</Data>");
				$new_strings.puts("                </Cell>")
				$new_strings.puts("            </Row>")
			end
		else
			if(id == "version") then
				d = DateTime.now()
				txt = "Version #{d.month}.#{d.day}"
			end
			if(id.match("task\\|")) then
				if($found_task[id] != nil) then
					$new_strings.puts("            <Row ss:Height=\"13.4064\">")
					$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
					$new_strings.puts("                    <Data ss:Type=\"String\">#{id}</Data>");
					$new_strings.puts("                </Cell>")
					$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
					$new_strings.puts("                    <Data ss:Type=\"String\">#{txt}</Data>");
					$new_strings.puts("                </Cell>")
					$new_strings.puts("            </Row>")
				end
			else
				if(id.match("location\\|")) then
					if($found_loc[id] != nil) then
						$new_strings.puts("            <Row ss:Height=\"13.4064\">")
						$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
						$new_strings.puts("                    <Data ss:Type=\"String\">#{id}</Data>");
						$new_strings.puts("                </Cell>")
						$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
						$new_strings.puts("                    <Data ss:Type=\"String\">#{txt}</Data>");
						$new_strings.puts("                </Cell>")
						$new_strings.puts("            </Row>")
					end
				else
					if(id.match("journal\\|")) then
						if($found_journ[id] != nil) then
							$new_strings.puts("            <Row ss:Height=\"13.4064\">")
							$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
							$new_strings.puts("                    <Data ss:Type=\"String\">#{id}</Data>");
							$new_strings.puts("                </Cell>")
							$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
							$new_strings.puts("                    <Data ss:Type=\"String\">#{txt}</Data>");
							$new_strings.puts("                </Cell>")
							$new_strings.puts("            </Row>")
						end
					else
						if(id.match("tut\\|")) then
							if($found_tut[id] != nil) then
								$new_strings.puts("            <Row ss:Height=\"13.4064\">")
								$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
								$new_strings.puts("                    <Data ss:Type=\"String\">#{id}</Data>");
								$new_strings.puts("                </Cell>")
								$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
								$new_strings.puts("                    <Data ss:Type=\"String\">#{txt}</Data>");
								$new_strings.puts("                </Cell>")
								$new_strings.puts("            </Row>")
							end
						else
							if(id.match("FLASH_")) then
								if($found_cut[id] != nil) then
									$new_strings.puts("            <Row ss:Height=\"13.4064\">")
									$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
									$new_strings.puts("                    <Data ss:Type=\"String\">#{id}</Data>");
									$new_strings.puts("                </Cell>")
									$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
									$new_strings.puts("                    <Data ss:Type=\"String\">#{txt}</Data>");
									$new_strings.puts("                </Cell>")
									$new_strings.puts("            </Row>")
								end
							else
								$new_strings.puts("            <Row ss:Height=\"13.4064\">")
								$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
								$new_strings.puts("                    <Data ss:Type=\"String\">#{id}</Data>");
								$new_strings.puts("                </Cell>")
								$new_strings.puts("                <Cell ss:StyleID=\"ce1\">")
								$new_strings.puts("                    <Data ss:Type=\"String\">#{txt}</Data>");
								$new_strings.puts("                </Cell>")
								$new_strings.puts("            </Row>")
							end
						end
					end
				end
			end
		end
	end
	$new_strings.puts("<Row ss:Index=\"65536\" ss:Height=\"12.8376\">");
    $new_strings.puts("<Cell ss:Index=\"2\" />");
    $new_strings.puts("</Row>");
end

def writeDialogs()
	Dir.foreach("./dialogs/"){|file|
		#puts "HAHA"+file.to_s
		if(file.match("conv")) then
			puts file
			writeConv(file)
		else
			if(file == ".." or file == ".") then
			
			else
				Dir.foreach("./dialogs/"+file+"/"){ |newfile|
					if(newfile.match("conv")) then
						puts file+"/"+newfile
						writeConv(file+"/"+newfile)
					end
				}
			end
		end
	}
end

done = false
writeDialogs()
#puts "!"+lines.to_s

for x in lines do
	$new_strings.puts(x)
	
	if(x.match("<Column ss:Width=\"699.7608\" />")) then
		writeHash()
	end

end
$new_strings.close
puts "Done"
