-- Licence: No care and no responsibility
-- Some code from the luatz project (MIT Licence)

-- Configuration ==========
local dateformat = "%Y-%m-%d, %H:%M"
local Colour_Not_Complete = "#FFB67D"
local Colour_Complete = "#000000"
local Colour_Heading_Complete = "#58FA58"
dofile "en.lua"	 -- default english translations
-- ========================
require( "iuplua" )
require( "iupluacontrols" )
dofile "../../SavedVariables/History.lua"

os.execute( "md ..\\..\\SavedVariables\\History_Bak" )  -- fails silently if already exists.

os.execute("copy  ..\\..\\SavedVariables\\History.lua ..\\..\\SavedVariables\\History_Bak\\History.lua")

function dump(o)
   if type(o) == 'table' then
      local s = '{ '
      for k,v in pairs(o) do
         if type(k) ~= 'number' then k = '"'..k..'"' end
         s = s .. '['..k..'] = ' .. dump(v) .. ','
      end
      return s .. '} '
   else
      return tostring(o)
   end
end
--local newf = assert(io.open("../../SavedVariables/History.new", "w"))

function write_saved(o)
   if type(o) == 'table' then
      local s = '{\n'
      for k,v in pairs(o) do
         if type(k) ~= 'number' then k = '"'..k..'"' end
         s = s .. '['..k..'] = ' .. write_saved(v) .. ',\n'
      end
      return s .. '}\n'
   else
      return tostring(o)
   end
end


for i,_ in pairs(History_SV["Default"]) do -- Only one entry
	myaccount = i
end

--Dump it back out
--newf:write("History_SV=" .. write_saved(History_SV))
--newf:close()

-- Load User Data

for i,_ in pairs(History_SV["Default"]) do -- Only one entry
	myaccount = i
end

local allchar = History_SV["Default"][myaccount]["$AccountWide"]["data"]
--get all character names into an array
local names = {} display = {}

 for char, _ in pairs(allchar) do
      table.insert (names, char)
	display[char] = {}
 end

-- print (dump(names))
--print (dump(display))
function getlevel(char) -- as numbers
	local level = 0
	for i,_ in pairs(allchar[char].levels) do
		if (i>level)  then
			level = i
		end
	end
	return level
end

function getlevel_as_text(char) -- as text and Vlevels
	local level = getlevel(char)
	if (level <=50) then
		return level
	else
		return "V" .. level -50
	end
end

Chartabs =iup.tabs{}
local leveling_box = {} Grp_box = {} Vet_box = {} Pub_box= {}

-- Creates boxes, stage from names to allow optional sorting in future.
for _,char in ipairs(names) do
	local gender=""
	if allchar[char].Gender =="M" then
		gender = L.Male
	elseif allchar[char].Gender =="F" then
		gender = L.Female
	end
	local level = getlevel(char)		-- as number
--	print (level, getlevel_as_text(char))
	local timeplayed = math.floor(allchar[char].levels[level].time/60)

	-- Generate the levelling box.  ============================
	-- Col 0 isn't used

	leveling_box[char] = iup.matrix {numcol=5, numcol_visible=5,  widthdef=60}
	leveling_box[char]:setcell(0,1, L.Level)
	leveling_box[char]:setcell(0,2, L.PTime)
	leveling_box[char]:setcell(0,3, L.Start)
	leveling_box[char]:setcell(0,4, L.Deaths)
	leveling_box[char]:setcell(0,5, L.APts)
	-- levels as stored are unsorted, so create a level table which is sorted,
	local levels = {}
	for i,_ in pairs(allchar[char].levels) do
		table.insert(levels, i)
	end

	table.sort(levels)


	for i,j in ipairs(levels) do		-- traverse in sorted order
	--	print (char, i,j)
		local timelevel = math.floor(allchar[char].levels[j].time)
		leveling_box[char].numlin = i
		leveling_box[char]:setcell(i,1, j)
		leveling_box[char]:setcell(i,2, math.floor(timelevel/60))
		leveling_box[char]:setcell(i,3, os.date("%Y-%m-%d",allchar[char].levels[j].begin))
		leveling_box[char]:setcell(i,4, allchar[char].levels[j].deaths)
		leveling_box[char]:setcell(i,5, allchar[char].levels[j].Ach_Points)
	end

	-- Create Grp Dungeon Achievements Box=========================

	Grp_box[char] = iup.matrix {numcol=4, numcol_visible=4,  numlin=5, widthdef=90}
	--Set Column titles
	for i=1, 4 do
		Grp_box[char]:setcell(0,i, Area_names[i].medium)
	end
	--set lines
	Grp_box[char]:setcell(0,0, L.Level)
	Grp_box[char]:setcell(1,0, "10+")
	Grp_box[char]:setcell(2,0, "17+")
	Grp_box[char]:setcell(3,0, "24+")
	Grp_box[char]:setcell(4,0, "31+")
	Grp_box[char]:setcell(5,0, "38+")

	-- set all text to red

	iup.SetAttribute(Grp_box[char],  "FGCOLOR*:1", Colour_Not_Complete)
	iup.SetAttribute(Grp_box[char],  "FGCOLOR*:2", Colour_Not_Complete)
	iup.SetAttribute(Grp_box[char],  "FGCOLOR*:3", Colour_Not_Complete)
	iup.SetAttribute(Grp_box[char],  "FGCOLOR*:4", Colour_Not_Complete)


	-- set text to black if achievement found.
	for id,_ in pairs (grp_dat) do
		local colour
		if allchar[char].ach[id] ~= nil then
			colour = "FGCOLOR" .. grp_dat[id].L .. ":" .. grp_dat[id].C
			iup.SetAttribute(Grp_box[char], colour, Colour_Complete)
		end
	end

	--Set background of heading if all done
	if allchar[char].ach[1073] ~= nil then  --EP Vanquisher
			iup.SetAttribute(Grp_box[char],  "BGCOLOR0:1", Colour_Heading_Complete)
	end

	if allchar[char].ach[1074] ~= nil then  --DC Vanquisher
			iup.SetAttribute(Grp_box[char],  "BGCOLOR0:2", Colour_Heading_Complete)
	end

	if allchar[char].ach[1075] ~= nil then  --AD Vanquisher
			iup.SetAttribute(Grp_box[char],  "BGCOLOR0:3", Colour_Heading_Complete)
	end


	for id,_ in pairs (grp_dat) do
			Grp_box[char]:setcell(grp_dat[id].L,grp_dat[id].C,grp_dat[id].name)
	end


	Grp_box[char].Redraw= "ALL"


	-- Create Pub Dungeon Achievements Box==========================
	Pub_box[char] = iup.matrix {numcol=4, numcol_visible=4,  numlin=5, widthdef=90}
	for i=1, 4 do  -- Load text
		Pub_box[char]:setcell(0,i, Area_names[i].medium)
	end
	Pub_box[char]:setcell(0,0, L.Level)
	Pub_box[char]:setcell(1,0, "12-15")
	Pub_box[char]:setcell(2,0, "20-23")
	Pub_box[char]:setcell(3,0, "35-36")
	Pub_box[char]:setcell(4,0, "40-43")
	Pub_box[char]:setcell(5,0, "47-50")

	iup.SetAttribute(Pub_box[char],  "FGCOLOR*:1", Colour_Not_Complete)
	iup.SetAttribute(Pub_box[char],  "FGCOLOR*:2", Colour_Not_Complete)
	iup.SetAttribute(Pub_box[char],  "FGCOLOR*:3", Colour_Not_Complete)
	iup.SetAttribute(Pub_box[char],  "FGCOLOR*:4", Colour_Not_Complete)

	for id,_ in pairs (pub_dat) do
		if allchar[char].ach[id] ~= nil then
			local colour = "FGCOLOR" .. pub_dat[id].L .. ":" .. pub_dat[id].C
			iup.SetAttribute(Pub_box[char], colour, Colour_Complete)
		end
	end

	if allchar[char].ach[1068] ~= nil then  --EP Conqueror
			iup.SetAttribute(Pub_box[char],  "BGCOLOR0:1", Colour_Heading_Complete)
	end

	if allchar[char].ach[1070] ~= nil then  --DC Conqueror
			iup.SetAttribute(Pub_box[char],  "BGCOLOR0:2", Colour_Heading_Complete)
	end

	if allchar[char].ach[1069] ~= nil then  --AD Conqueror
			iup.SetAttribute(Pub_box[char],  "BGCOLOR0:3", Colour_Heading_Complete)
	end

	for id,_ in pairs (pub_dat) do  -- Load text
			Pub_box[char]:setcell(pub_dat[id].L,pub_dat[id].C,pub_dat[id].name)
	end

	Pub_box[char].Redraw= "ALL"


	-- Create Vet Dungeon Achievements Box==========================
	Vet_box[char] = iup.matrix {numcol=5, numcol_visible=5,  numlin=5, widthdef=110}

	for i=1, 5 do  -- Load headings
		Vet_box[char]:setcell(0,i, Area_names[i].medium)
	end

	iup.SetAttribute(Vet_box[char],  "FGCOLOR*:1", Colour_Not_Complete)
	iup.SetAttribute(Vet_box[char],  "FGCOLOR*:2", Colour_Not_Complete)
	iup.SetAttribute(Vet_box[char],  "FGCOLOR*:3", Colour_Not_Complete)
	iup.SetAttribute(Vet_box[char],  "FGCOLOR*:4", Colour_Not_Complete)
	iup.SetAttribute(Vet_box[char],  "FGCOLOR*:5", Colour_Not_Complete)

	-- Need to keep track of multiple achievements in Vet dungeons. Index them by dungeon LineColumn.
	Vet_Info={}
	for id,_ in pairs (vet_dat) do  -- Load Dungeons Info LC is the Dungeon Identifier
			local L = vet_dat[id].L
			local C = vet_dat[id].C
			Vet_Info[L..C] = {count = 0}
			Vet_box[char]:setcell(L,C,vet_dat[id].name .. " (0)")
	end


	for id,_ in pairs (vet_dat) do  -- For Achievements we have..
		if allchar[char].ach[id] ~= nil then
			local L = vet_dat[id].L
			local C = vet_dat[id].C
			--Set colour of LC
			local colour = "FGCOLOR" .. L .. ":" .. C
			iup.SetAttribute(Vet_box[char], colour, Colour_Complete)

			-- Increment count and display
			Vet_Info[L..C].count = Vet_Info[L..C].count+1
			Vet_box[char]:setcell(L,C,vet_dat[id].name .. " (" .. Vet_Info[L..C].count ..")")
		end
	end

	if allchar[char].ach[1159] ~= nil 	then -- Coh All special.
		iup.SetAttribute(Vet_box[char], "FGCOLOR3:3", Colour_Heading_Complete)
	end

	if allchar[char].ach[1139] ~= nil 	then -- Craglorn all special.
		iup.SetAttribute(Vet_box[char], "BGCOLOR0:5", Colour_Heading_Complete)
	end




	Vet_box[char].Redraw= "ALL"

 -- ====================================




	display[char]["vbox"] = iup.vbox{
				["tabtitle"] = char,		-- This vbox will be a tab and the tab text is this

				iup.hbox{		--Top Information bar
						iup.label{title=gender, FONT="Times,BOLD,10"},
						iup.label{title=allchar[char].Race .." / ".. allchar[char].Class, PADDING="10X0", FONT="Times,BOLD,10"},
						iup.label{title=allchar[char].Alliance, PADDING="10X0"},
						iup.label{title=L.Level .. ": ".. getlevel_as_text(char), PADDING="10X0"},
						iup.label{title="Created: ".. os.date(dateformat,allchar[char].Recorded), PADDING="10X0"},
						iup.label{title="Last Login: ".. os.date(dateformat,allchar[char].LoginTime), PADDING="10X0"},
						iup.label{title="Time Played: ".. timeplayed .. L.Hrs},
						iup.fill{}
						},
				iup.label{SEPARATOR="HORIZONTAL"},
				iup.vbox {		--Data tabs for Char
					iup.tabs { iup.vbox {	["tabtitle"] =L.GrpDungeon,
											iup.label{title="Levels are Minimum, scales to leader",expand="HORIZONTAL"},
											Grp_box[char],
											iup.fill{}
										},
								iup.vbox {	["tabtitle"] =L.PubDungeon,
											iup.label{title="PubLabel",expand="HORIZONTAL"},
											Pub_box[char],
											iup.fill{}
										},
								iup.vbox {	["tabtitle"] =L.VetDungeon,
											iup.label{title="All are V1-V12 except City of Ash which is V13-V14",expand="HORIZONTAL"},
											Vet_box[char],
											iup.fill{}
										},

								iup.vbox {	["tabtitle"] =L.Leveling,
											iup.label{title="LevLabel",expand="HORIZONTAL"},
											leveling_box[char],
											iup.fill{}
										},
							},
				},

			--	iup.label{title="char", expand="HORIZONTAL"},
				iup.label{SEPARATOR="HORIZONTAL"},	-- Bottom Area
				iup.button{title="Button", FGCOLOR = "#FF0080"},
				}
	iup.Append(Chartabs,display[char]["vbox"])
end

local panelsize = (#names*80+100) .. "x250"

-- Creates dialog
dlg = iup.dialog{iup.vbox{Chartabs; margin="10x10"}; title="History For  " .. myaccount, size=panelsize}

-- Shows dialog in the center of the screen
dlg:showxy(iup.CENTER, iup.CENTER)

if (iup.MainLoopLevel()==0) then
  iup.MainLoop()
end