 -----
-----	Just a placeholder file I use for testing.
-----
local _
local DEFAULT_VALUE = 42/255
local keyColorCode = {}
local modColorCode = {}
local inCombat = false
local settingsUpdate = false
local keyCode={
--	192/255, 222/255,   8/255, 190/255, 186/255,
--	 44/255, 191/255, 189/255, 187/255, 188/255, 220/255,
--	219/255, 221/255,  33/255,  34/255,  35/255,  36/255,
--	 37/255,  38/255,  39/255,  40/255,  45/255,  46/255,
--	106/255, 107/255, 110/255, 111/255,  32/255, 
}
local keyText = {
--	             "`",          "'",     "BACKSPACE",            ".",      ";",
--	   "PRINTSCREEN",          "/",             "-",            "=",      ",",     "\\",
--	             "[",          "]",        "PAGEUP",     "PAGEDOWN",    "END",   "HOME",
--	          "LEFT",         "UP",         "RIGHT",         "DOWN", "INSERT", "DELETE",
--	"NUMPADMULTIPLY", "NUMPADPLUS", "NUMPADDECIMAL", "NUMPADDIVIDE",  "SPACE",
}

local ascii
for ascii = 112, 114 do -- F1-F3
	table.insert(keyCode, ascii/255)
	table.insert(keyText, "F" .. (ascii-111))
end
for ascii = 116, 119 do -- F5-F8 
	table.insert(keyCode, ascii/255)
	table.insert(keyText, "F" .. (ascii-111))
end
for ascii = 96, 105 do -- Numberpad 0-9
	table.insert(keyCode, ascii/255)
	table.insert(keyText, "NUMPAD" .. (ascii-96))
end
for ascii = 65, 90 do -- A-Z
	table.insert(keyCode, ascii/255)
	table.insert(keyText, string.char(ascii))
end
for ascii = 48, 57 do -- 0-9
	table.insert(keyCode, ascii/255)
	table.insert(keyText, string.char(ascii))
end

local modifierCode= { 
	3/255, 9/255, 10/255, 
	11/255, 1/255, 2/255
}
local modifierText= {
	"CTRL-SHIFT-", "ALT-SHIFT-", "ALT-CTRL-", 
	"ALT-CTRL-SHIFT-", "SHIFT-", "CTRL-"
}

local temp1, temp2

local lastTime = GetTime()
local frame = CreateFrame("Frame")
frame:SetSize(1,1)
frame:SetFrameStrata("TOOLTIP")
frame:SetPoint("TOPLEFT")
frame.texture = frame:CreateTexture("bg", "BACKGROUND", "ActionBarButtonTemplate")
frame.texture:SetAllPoints(frame)
frame.texture:SetColorTexture(0,0,1,1)
frame:Show()

local frame2 = CreateFrame("Frame")
frame2:SetSize(1,1)
frame2:SetFrameStrata("TOOLTIP")
frame2:SetPoint("TOPLEFT",1,0)
frame2.texture = frame2:CreateTexture("bg2", "BACKGROUND", "ActionBarButtonTemplate")
frame2.texture:SetAllPoints(frame2)
frame2.texture:SetColorTexture(0,0,1,1)
frame2:Show()


local frame3 = CreateFrame("Frame")
frame3:SetSize(1,1)
frame3:SetFrameStrata("TOOLTIP")
frame3:SetPoint("TOPLEFT",2,0)
frame3.texture = frame3:CreateTexture("bg2", "BACKGROUND", "ActionBarButtonTemplate")
frame3.texture:SetAllPoints(frame3)
frame3.texture:SetColorTexture(0,0,1,1)
frame3:Show()

local frame4 = CreateFrame("Frame")
frame4:SetSize(1,1)
frame4:SetFrameStrata("TOOLTIP")
frame4:SetPoint("TOPLEFT",3,0)
frame4.texture = frame4:CreateTexture("bg2", "BACKGROUND", "ActionBarButtonTemplate")
frame4.texture:SetAllPoints(frame4)
frame4.texture:SetColorTexture(0,0,1,1)
frame4:Show()

local lastUpdate = 0;
local record = false
local stopRecordAt
local startRecordAt

local events = {}
local buttons = {}
local btn

local bindings = {}

function PRINTKEYS()
	for key,value in pairs(_G) do
		if(string.upper(string.sub(key,1,3))=="KEY") then
			print(key,"=",value)
		end
	end
end

function events:PLAYER_REGEN_ENABLED() 
	inCombat = false
	stopRecordAt = GetTime() + 3
	if settingsUpdate then
		WhatsNext:ApplyExtensionSettings()
	end
end

function events:PLAYER_REGEN_DISABLED() 
	inCombat = true
	record = true
end

local eventHandler = CreateFrame("Frame", nil, WorldFrame)


local function ToBlockID(block)
	local type = strupper(block.type or "SPELL");
	if(type == "SPELL") then
		return "SPELL " .. (GetSpellInfo(block.spell) or block.text) .. (block.unit and (" " ..block.unit) or "")
	elseif type == "ITEM" and GetItemInfo(block.item) then
		return "ITEM " .. GetItemInfo(block.item)
	elseif type == "MACRO" and GetMacroInfo(block.macro) then
		return "MACRO " .. GetMacroInfo(block.macro);		
	end
	return nil
end

function UpdateCorderFrame(self)
	record = WN_GetDBMBar("Pull In") or inCombat or UnitIsDead("player")
	if record then
		stopRecordAt = nil
	elseif not stopRecordAt then
		stopRecordAt = GetTime() + 4
		record = true
	elseif stopRecordAt > GetTime() then
		record = true
	end
	
	frame2.texture:SetColorTexture( record and 1 or 0, DEFAULT_VALUE,DEFAULT_VALUE, 1)
	frame3.texture:SetColorTexture( (UnitCreatureType("mouseover") == "Wild Pet") and 1 or 0, DEFAULT_VALUE,DEFAULT_VALUE, 1)
	frame4.texture:SetColorTexture( PetBattleFrame:IsVisible() and 1 or 0, DEFAULT_VALUE,DEFAULT_VALUE, 1)
	
	local suggestion = WhatsNext.suggestions[1];
	local _, _, _, _, _, endTime, _, _, _ = UnitCastingInfo("player");
	
	if not endTime then
		_, _, _, _, _, endTime, _, _, _ = UnitChannelInfo("player");
	end
	
	local  remainingTime;
	if endTime then
		remainingTime = endTime - (GetTime()*1000);
	end
	
	if not suggestion then
		frame:Hide()
	elseif suggestion.type and suggestion.type ~= "spell" and suggestion.type ~= "item" and suggestion.type ~= "macro" then
		frame:Hide()
	elseif CursorHasItem() or GetCurrentKeyBoardFocus() or SpellIsTargeting() then
		frame:Hide()
	elseif UnitIsAFK("player") or (remainingTime and remainingTime > 400 ) then
		frame:Hide()
	else
		local actionText = ToBlockID(suggestion)
		if actionText and keyColorCode[actionText] and modColorCode[actionText]  then
			frame:Show()
			--print(keyColorCode[actionText]);
			frame.texture:SetColorTexture( keyColorCode[actionText] or nil, modColorCode[actionText] or nil, DEFAULT_VALUE, 1)
		end
	end
end

eventHandler:SetScript("OnUpdate", function(self)	
	retOk,bound = pcall(UpdateCorderFrame,self)
	if not retOk then
		print(bound)
	end
end)

local function EventFunc(self, event, ...)
	events[event](event, ...)
end
local eventHandler = CreateFrame("Frame", nil, WorldFrame)
eventHandler:SetScript("OnEvent", EventFunc)
for eventname in pairs(events) do eventHandler:RegisterEvent(eventname) end	

local function ToString(bool)
	return bool and "true" or "false"
end

local function SetKeyBind(i,block,modifier)
	local actionText = ToBlockID(block)	
	--print(actionText)
	if actionText and not keyColorCode[actionText] then
		local bindText = modifierText[modifier]..keyText[i]
		--print(bindText,actionText)
		keyColorCode[actionText] = keyCode[i]
		modColorCode[actionText] = modifierCode[modifier]
		
		if(strupper(block.type) == "SPELL") and block.unit then
			local button_i = #keyCode * modifier + i
			local btnName = "WNExtButton"..button_i
			btn = buttons[button_i]
			if not btn then
				btn = CreateFrame("Button", btnName, UIParent, "SecureActionButtonTemplate");
				btn:SetAttribute("type", "spell");
				buttons[button_i] = btn
			end
			btn:SetAttribute("spell", GetSpellInfo(block.spell));
			if block.unit then
				btn:SetAttribute("unit", block.unit);
			end
			
			if bindings[bindText] ~= btnName then
				bindings[bindText]=btnName
				SetBindingClick(bindText,btnName)
				--print ("Bound Click: " , bindText , " - " + actionText)
			end
		else
			if bindings[bindText] ~= actionText then
				bindings[bindText]=actionText
				SetBinding(bindText,actionText)
				--print ("Bound: " , bindText , " - " ,actionText)
				
			end
		end
		return true
	end
	return nil
end


function WhatsNext:ApplyExtensionSettings()
	if inCombat then
		settingsUpdate = true
		return
	end
	if GetTime() - 6 < lastUpdate then
		print("Exp: Blocked, too soon,")
		return
	end
	
	settingsUpdate = false
	wipe(keyColorCode)
	wipe(modColorCode)
	local i,modifier,retOK,bound = 1,1
	if self.castSequence then
		for _,block in ipairs(self.castSequence) do
			retOk,bound = pcall(SetKeyBind,i,block,modifier)
			if retOk and bound then
				if i >= #keyCode then
					i = 1
					modifier = modifier + 1
				else
					i = i + 1
				end
			elseif not retOk then
				print(bound)
			end
		end
	end
	SaveBindings(2)
	lastUpdate = GetTime()
end