-- 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")

-- ============== Setup storage for old characters.
archivef = io.open("../../SavedVariables/History.Archive", "r")
if archivef ==nil then	--create empty file
	archivef = io.open("../../SavedVariables/History.Archive", "w")
	archivef:write("Archive = {} \n")
end
archivef:close()
dofile "../../SavedVariables/History.Archive"
-- ==============

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
-- newf = assert(io.open("../../SavedVariables/History.new", "w"))

-- Minimally effective quoting
function quote(astring)
	return '"' .. string.gsub(astring,"%'", "\\'") .. '"'
end


function write_saved(o)
	local escaped
   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'
   elseif
		type(o) == 'string' then
		return quote(o)
   else
		return tostring(o)
   end
end


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

function write_data()
  newf = assert(io.open("../../SavedVariables/History.new", "w"))
  newf:write("History_SV=" .. write_saved(History_SV))
  newf:close()
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 print_old()
	for i,j in pairs (History_SV["Default"][myaccount]["$AccountWide"]["old"]) do
		print (i .. " .. " .. j)
	end

end
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

lbl_Status_bar = iup.label{title=L.Welcome, expand = "HORIZONTAL"}
btn_archive = iup.button{title="Archive", FGCOLOR = "#FF0000"}
logtabs  =iup.tabs{}  -- Examine Log Data
Chartabs =iup.tabs{}  -- Character Info in Here

-- 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.  ============================
	local leveling_box = {}
	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=========================
	local Grp_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==========================
	local Pub_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==========================
	local Vet_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=L.Created .. os.date(dateformat,allchar[char].Recorded), PADDING="10X0"},
						iup.label{title=L.LLog .. os.date(dateformat,allchar[char].LoginTime), PADDING="10X0"},
						iup.label{title=L.TPlayed .. 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=L.GrpLab,expand="HORIZONTAL"},
											Grp_box[char],
											iup.fill{}
										},
								iup.vbox {	["tabtitle"] =L.PubDungeon,
											iup.label{title=L.PubLab,expand="HORIZONTAL"},
											Pub_box[char],
											iup.fill{}
										},
								iup.vbox {	["tabtitle"] =L.VetDungeon,
											iup.label{title=L.VetLab,expand="HORIZONTAL"},
											Vet_box[char],
											iup.fill{}
										},

								iup.vbox {	["tabtitle"] =L.Leveling,
											iup.label{title="LevLabel",expand="HORIZONTAL"},
											leveling_box[char],
											iup.fill{}
										},
							},	-- end of tabs for dungeons
						},
				}  -- end of tabs for characters vbox
	iup.Append(Chartabs,display[char]["vbox"])
end
-- Now create the Log panel


local logtable =iup.matrix{numcol=1, numcol_visible=1,  numlin=0}
	logtable:setcell(0,1, L.TStamp)
	iup.SetAttribute(logtable,  "WIDTH0", 0)
	iup.SetAttribute(logtable,  "WIDTH1", 200)


function Load_Log()
	local Line=0
	logtable.numlin = Line
	for i,j in ipairs (History_SV["Default"][myaccount]["$AccountWide"]["log"]) do
		Line= Line +1
		logtable.numlin = Line
		logtable:setcell( Line,1, j)
	end
end

-- Load the log first time
Load_Log()
print_old()

btn_eraselog=iup.button{title=L.EraseButton, FGCOLOR = "#FF0000"}


local log_box=iup.vbox {
	["tabtitle"] =L.LogTab,
	iup.label{title="LogLabel",expand="HORIZONTAL"},
	logtable,
	iup.label{SEPARATOR="HORIZONTAL"},	-- Bottom Area
	iup.hbox {
		btn_eraselog,
		iup.label{title = L.EraseWarning, PADDING="10X0"},
		iup.fill{}
	},
	iup.fill{}
}
function btn_eraselog:action()
	History_SV["Default"][myaccount]["$AccountWide"]["log"] = {}
 	write_data()	-- write new history
 	Load_Log()
	lbl_Status_bar.title = L.Erased
end
-- Add to end of Characters
iup.Append(Chartabs, log_box)

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

-- Create dialog
dlg = iup.dialog{iup.vbox{Chartabs,
						iup.hbox{lbl_Status_bar,	-- Bottom Status bar.
								iup.fill{},
								},
						margin="5x5",
						},
				title=L.title .. 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