-- This file is executed once on we start up.  The state perseveres
-- through callbacks
--
-- wehack.runprocess:  Wait for exit code, report errors (grimext)
-- wehack.runprocess2:  Wait for exit code, don't report errors (jasshelper)
-- wehack.execprocess:  Don't wait for exit code (War3)
--
grimregpath = "Software\\Grimoire\\"
--warcraftdir = grim.getregpair(grimregpath,"War3InstallPath")
--if warcraftdir == 0 then
--	wehack.messagebox("Error, could not find warcraft install path in wehack.lua")
--end
grimdir = grim.getcwd()

dofile("wehacklib.lua")
dofile("findpath.lua")
mapvalid = true
cmdargs = "" -- used to execute external tools on save

confregpath = "HKEY_CURRENT_USER\\Software\\Grimoire\\"

haveext = grim.exists("grimext\\mpqcom.dll")
if haveext then
    utils = wehack.addmenu("Extensions")
end

whmenu = wehack.addmenu("Grimoire")
wh_window = TogMenuEntry:New(whmenu,"Start War3 with -window",nil,true)
wh_opengl = TogMenuEntry:New(whmenu,"Start War3 with -opengl",nil,true)
wh_grimoire = TogMenuEntry:New(whmenu,"Start War3 with Grimoire",nil,true)
wehack.addmenuseparator(whmenu)
wh_nolimits = TogMenuEntry:New(whmenu,"Enable no limits",
	function(self) grim.nolimits(self.checked) end,true)
wh_oehack = TogMenuEntry:New(whmenu,"Enable object editor hack",
	function(self) grim.objecteditorhack(self.checked) end)
wh_syndisable = TogMenuEntry:New(whmenu,"Disable WE syntax checker",
	function(self) grim.syndisable(self.checked) end,true)
wh_descpopup = TogMenuEntry:New(whmenu,"Disable default description nag",
	function(self) grim.descpopup(self.checked) end,true)
wh_autodisable = TogMenuEntry:New(whmenu,"Don't let WE disable triggers",
	function(self) grim.autodisable(self.checked) end,true)
wh_alwaysenable = TogMenuEntry:New(whmenu,"Always allow trigger enable",
	function(self) grim.alwaysenable(self.checked) end,true)
wh_enablewar3err = TogMenuEntry:New(whmenu,"Enable war3err",nil,true)

weukey = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\WE Unlimited_is1"
weuval = "InstallLocation"
weupath = grim.getregpair(weukey,weuval)
haveweu = grim.exists(weupath .. "WE Unlimited.exe")
if haveweu then
	wh_useweu = TogMenuEntry:New(whmenu,"Integrate WEU",nil,false)
end

usetestmapconf = (grim.getregpair(confregpath,"Use custom test map settings") == "on")
function testmapconfig()
	usetestmapconf = wehack.testmapconfig(path,usetestmapconf)
	if usetestmapconf then
		grim.setregstring(confregpath,"Use custom test map settings","on")
	else
		grim.setregstring(confregpath,"Use custom test map settings","off")
	end
end
wh_configtest = MenuEntry:New(whmenu,"Customize test map settings",testmapconfig);

function aboutpopup()
	wehack.showaboutdialog("Grimoire 1.4")
end
wh_about = MenuEntry:New(whmenu,"About",aboutpopup)

havejh = grim.exists("jasshelper\\jasshelper.exe")
if havejh then
	jhmenu = wehack.addmenu("JassHelper")
	jh_enable = TogMenuEntry:New(jhmenu,"Enable JassHelper")
	jh_debug = TogMenuEntry:New(jhmenu,"Debug Mode")
	jh_disable = TogMenuEntry:New(jhmenu,"Disable vJass syntax")
end

function initshellext()
    local first, last = string.find(grim.getregpair("HKEY_CLASSES_ROOT\\WorldEdit.Scenario\\shell\\open\\command\\", ""),"%%L",1)
    if first then
        wehack.checkmenuentry(shellext.menu,shellext.id,1)
    else
        wehack.checkmenuentry(shellext.menu,shellext.id,0)
    end
end

function fixopencommand(disable,filetype)
    local curval = grim.getregpair("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\open\\command\\","")
    if curval ~= 0 then
        if disable then
            grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\open\\command\\","",string.gsub(curval, "%%L", "%%1"))
        else
            grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\open\\command\\","",string.gsub(curval, "%%1", "%%L"))
        end
    end
end

function registerextension(disable,warpath,filetype,istft)
    if disable then
        grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\command\\");
        grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\");
        grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\command\\");
        grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\");
    else
        if istft then
            gamepath = "\""..warpath.."\\Frozen Throne.exe\""
        else
            gamepath = "\""..warpath.."\\Warcraft III.exe\""
        end
        grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\","","Play Fullscreen")
        grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\command\\","",gamepath.." -loadfile \"%L\"")
        grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\","","Play Windowed")
        grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\command\\","",gamepath.." -window -loadfile \"%L\"")
    end
end

function toggleshellext()
    local istft = (grim.getregpair("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "InstallPathX") ~= 0)
    local first, last = string.find(grim.getregpair("HKEY_CLASSES_ROOT\\WorldEdit.Scenario\\shell\\open\\command\\", ""),"%%L",1)
    if path ~= 0 then
        fixopencommand(first,"Scenario")
        registerextension(first,path,"Scenario",istft)
        fixopencommand(first,"ScenarioEx")
        registerextension(first,path,"ScenarioEx",istft)
        fixopencommand(first,"Campaign")
        registerextension(first,path,"Campaign",istft)
        fixopencommand(first,"AIData")
        if first then
            wehack.checkmenuentry(shellext.menu,shellext.id,0)
        else
            wehack.checkmenuentry(shellext.menu,shellext.id,1)
        end
    end
end

function initlocalfiles()
    if grim.getregpair("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "Allow Local Files") == 0 then
        wehack.checkmenuentry(localfiles.menu,localfiles.id,0)
    else
        wehack.checkmenuentry(localfiles.menu,localfiles.id,1)
    end
end

function togglelocalfiles()
    if grim.getregpair("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "Allow Local Files") == 0 then
        grim.setregdword("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "Allow Local Files", 1)
        wehack.checkmenuentry(localfiles.menu,localfiles.id,1)
    else
        grim.setregdword("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "Allow Local Files", 0)
        wehack.checkmenuentry(localfiles.menu,localfiles.id,0)
    end
end

function runobjectmerger()
    curmap = wehack.findmappath()
    if curmap ~= "" then
        source = wehack.openfiledialog("Unit files (*.w3u)|*.w3u|Item files (*.w3t)|*w3t|Doodad files (*.w3d)|*.w3d|Destructable files (*.w3b)|*.w3b|Ability files (*.w3a)|*.w3a|Buff files (*.w3h)|*.w3h|Upgrade files (*.w3q)|*.w3q|", "w3a", "Select files to import ...", true)
        if source ~= "" then
            list = strsplit("|", source);
            cmdargs = "grimext\\ObjectMerger.exe \""..curmap.."\" "..wehack.getlookupfolders()..fileargsjoin(list)
--            wehack.messagebox(cmdargs,"Grimoire",false)
            wehack.savemap()
        end
    end
end

function runconstantmerger()
    curmap = wehack.findmappath()
    if curmap ~= "" then
        source = wehack.openfiledialog("Text files (*.txt)|*.txt|", "txt", "Select files to import ...", true)
        if source ~= "" then
            list = strsplit("|", source);
            cmdargs = "grimext\\ConstantMerger.exe \""..curmap.."\" "..wehack.getlookupfolders()..fileargsjoin(list)
--            wehack.messagebox(cmdargs,"Grimoire",false)
            wehack.savemap()
        end
    end
end

function runtriggermerger()
    curmap = wehack.findmappath()
    if curmap ~= "" then
        source = wehack.openfiledialog("GUI Trigger files (*.wtg)|*.wtg|Custom Text Trigger files (*.wct)|*wct|", "wtg", "Select trigger data to import ...", true)
        if source ~= "" then
            list = strsplit("|", source);
            cmdargs = "grimext\\TriggerMerger.exe \""..curmap.."\" "..wehack.getlookupfolders()..fileargsjoin(list)
--            wehack.messagebox(cmdargs,"Grimoire",false)
            wehack.savemap()
        end
    end
end

function runfileimporterfiles()
    curmap = wehack.findmappath()
    if curmap ~= "" then
        source = wehack.openfiledialog("All files (*.*)|*.*|", "*", "Select files to import ...", true)
        if source ~= "" then
            list = strsplit("|", source);
            inmpqpath = wehack.inputbox("Specify the target path ...","FileImporter","Units\\")
            cmdargs = "grimext\\FileImporter.exe \""..curmap.."\" "..wehack.getlookupfolders()..argsjoin(inmpqpath,list)
--            wehack.messagebox(cmdargs,"Grimoire",false)
            wehack.savemap()
        end
    end
end

function runfileimporterdir()
    curmap = wehack.findmappath()
    if curmap ~= "" then
        source = wehack.browseforfolder("Select the source directory ...")
        if source ~= "" then
            cmdargs = "grimext\\FileImporter.exe \""..curmap.."\" "..wehack.getlookupfolders().." \""..source.."\\\""
--            wehack.messagebox(cmdargs,"Grimoire",false)
            wehack.savemap()
        end
    end
end

function runfileexporter()
    curmap = wehack.findmappath()
    if curmap ~= "" then
        target = wehack.browseforfolder("Select the target directory ...")
        if target ~= "" then
            wehack.runprocess("grimext\\FileExporter.exe \""..curmap.."\" "..wehack.getlookupfolders().." \""..target.."\\\"")
        end
    end
end

function runtilesetter()
    curmap = wehack.findmappath()
    if curmap ~= "" then
        map = wehack.openarchive(curmap,15)
        oldtiles = wehack.getcurrenttiles()
        wehack.closearchive(map)
	 if oldtiles ~= "" then
	    tileset = wehack.inputbox("Specify the tileset ...","TileSetter",string.sub(oldtiles,1,1))
            if tileset ~= "" then
                tiles = wehack.inputbox("Specify the tile list ...","TileSetter",string.sub(oldtiles,2))
                if tiles ~= "" then
                    cmdargs = "grimext\\TileSetter.exe \""..curmap.."\" "..wehack.getlookupfolders().." "..tileset.." "..tiles
--                    wehack.messagebox(cmdargs,"Grimoire",false)
                    wehack.savemap()
                end
            end
        end
    end
end

function testmap(cmdline)
	--if havejh and jh_enable.checked and not mapvalid then
	--	return
	--end
	--wehack.messagebox(cmdline)
	--mappath = strsplit(" ",cmdline)[2]
	--compilemap_path(mappath)
	
	if wh_opengl.checked then
		cmdline = cmdline .. " -opengl"
	end
	if wh_window.checked then
		cmdline = cmdline .. " -window"
	end
	if wh_grimoire.checked then
--		local args = string.gsub(cmdline,"\"([^\"]*)\" ","")
--		wehack.messagebox(args,"Grimoire",false)
--		cmdline = "startwar3.bat " .. args

		local testmaparglist = argsplit(cmdline)
		local len = table.getn(testmaparglist)
		if len > 2 then
			cmdline = "startwar3.bat"
			for i = 2, len do
				if (i < len) and (usetestmapconf) then
					local arglen = string.len(testmaparglist[i+1])
					if testmaparglist[i] == "-loadfile" and arglen > 3 then
						local ext = string.lower(string.sub(testmaparglist[i+1],arglen-4+1))
						if ext == ".w3m" or ext == ".w3x" then
							local substitute = wehack.setupwgcfile(testmaparglist[i+1]);
							if (substitute ~= testmaparglist[i+1]) then
								testmaparglist[i+1] = "\"" .. substitute .. "\""
							end
						end
					end
				end
				cmdline = cmdline .. " " .. testmaparglist[i]
			end
		end

	end
	wehack.execprocess(cmdline)
end

function compilemap_path(mappath)
	if mappath == "" then
		wehack.messagebox("Could not find path to map, please try saving again","Grimoire",false)
		return
	end
	map = wehack.openarchive(mappath,15)
	--wehack.extractfile("jasshelper\\common.j","scripts\\common.j")
	--wehack.extractfile("jasshelper\\Blizzard.j","scripts\\Blizzard.j")
	wehack.extractfile("war3map.j","war3map.j")
	wehack.closearchive(map)
	if cmdargs ~= "" then
		wehack.runprocess(cmdargs)
		cmdargs = ""
	end
wehack.runprocess2("AdicHelper\\Autoreplacer.exe \"" .. mappath .. "\"")
wehack.runprocess2("AdicHelper\\AdicHelper.exe /mappath=\"" .. mappath .. "\"")

	if havejh and jh_enable.checked then
		cmdline = "jasshelper\\jasshelper.exe"
		if jh_debug.checked then
			cmdline = cmdline .. " --debug"
		end
		if jh_disable.checked then
			cmdline = cmdline .. " --nopreprocessor"
		end
		cmdline = cmdline .. " jasshelper\\common.j jasshelper\\blizzard.j \"" .. mappath .."\""
		if wehack.runprocess2(cmdline) == 0 then
			mapvalid = true
		else
			mapvalid = false
		end
	end
end

function compilemap()
	mappath = wehack.findmappath()
	compilemap_path(mappath)
end

if haveext then
    localfiles = MenuEntry:New(utils,"Enable Local Files",togglelocalfiles)
    shellext = MenuEntry:New(utils,"Register Shell Extensions",toggleshellext)
    initlocalfiles()
    initshellext()
end
if haveext and grim.exists("grimext\\tilesetter.exe") then
    tilesetter = MenuEntry:New(utils,"Edit Tileset",runtilesetter)
end
if haveext and grim.exists("grimext\\fileexporter.exe") then
    fileexporter = MenuEntry:New(utils,"Export Files",runfileexporter)
end
if haveext and grim.exists("grimext\\fileimporter.exe") then
    fileimporterdir = MenuEntry:New(utils,"Import Directory",runfileimporterdir)
    fileimporterfiles = MenuEntry:New(utils,"Import Files",runfileimporterfiles)
end
if haveext and grim.exists("grimext\\objectmerger.exe") then
    objectmerger = MenuEntry:New(utils,"Merge Object Editor Data",runobjectmerger)
end
if haveext and grim.exists("grimext\\constantmerger.exe") then
    constantmerger = MenuEntry:New(utils,"Merge Constants Data",runconstantmerger)
end
if haveext and grim.exists("grimext\\triggermerger.exe") then
    triggermerger = MenuEntry:New(utils,"Merge Trigger Data",runtriggermerger)
end

function jhshowerr()
    wehack.execprocess("jasshelper\\jasshelper.exe --showerrors")
end

function jhabout()
    wehack.execprocess("jasshelper\\jasshelper.exe --about")
end

if havejh then
     jhshowerrm = MenuEntry:New(jhmenu,"Show previous errors",jhshowerr)
     jhaboutm = MenuEntry:New(jhmenu,"About JassHelper...",jhabout)
end

