hist = {
	name = "History",
	version = "1",
	initialised = false,
	SV={},
	L={},
	me = {},
	player = "",
	last="",
	tz_offset =0,
	debug = false
}



local function log(text)
	local nowstring = GetTimeString()
	table.insert(hist.SV.log,nowstring .. ": " .. text)
end
local function Achievement(_, name, points, id, link)
	local description
	local category_id  = GetCategoryInfoFromAchievementId(id)
	local category_name =GetAchievementCategoryInfo(category_id)
		_,description,_,_,_,_,_= GetAchievementInfo(i)
	hist.me.ach[id]={
		["Category_ID"] = category_id,
		["Category"] = category_name,
		["time"] = GetTimeStamp(),
		["points"] = points,
		["name"] = name,
		["description"] = description,
		["link"] = link
		}

      if hist.debug then
        d("Achievement Awarded:.. ")
        d(hist.me.ach[id])
      end
end

local function  log_clear()
	hist.SV.log = {}
	log("Cleared")
end
function load_history()
-- load up historic Achievements for Category 7  (Dungeons)
	log("Request to load historic Dungeon Achievements")
	local name,points,description,completed,adate,atime
	for i = 1,1400 do
		name,description,points,_,completed,adate,atime= GetAchievementInfo(i)
		if completed then
			cat,_,_ =GetCategoryInfoFromAchievementId(i)
			if cat == 7 then
				if hist.me.ach[i] == nil then
					log("Added historic achievement " ..i .. " " .. name)
						local category_id  = GetCategoryInfoFromAchievementId(id)
						local category_name =GetAchievementCategoryInfo(category_id)
						hist.me.ach[i]={
							["Category_ID"] = category_id,
							["Category"] = category_name,
							["time"] = (luatz_esodate(adate .. " " .. atime)+ hist.tz_offset),
							["points"] = points,
							["name"] = name,
							["description"] = description,
							["link"] = GetAchievementLink(i)
							}

				end
			end
		end
	end
end

local function fix()  -- fix links etc for any old data
local description
	hist.me.ach_updates = nil
	log("Request to fix Achievement data")
 for i,_ in pairs(hist.me.ach) do
 		_, description,_,_,_,_,_= GetAchievementInfo(i)
		local category_id  = GetCategoryInfoFromAchievementId(i)
		local category_name =GetAchievementCategoryInfo(category_id)
		hist.me.ach[i]["Category_ID"] = category_id
		hist.me.ach[i]["Category"] = category_name
		hist.me.ach[i]["description"] = description
		hist.me.ach[i]["link"] = GetAchievementLink(i)
 end
end


local function Activated()
	hist.me.levels[hist.me.level].time = math.floor(GetSecondsPlayed() /60)
end


local function levelup(eventCode, unitTag,_)
	if unitTag == "player" then
	local oldlevel = hist.me.level
	hist.me.level =  GetUnitLevel("player") + GetUnitVeteranRank("player")
	log("Levelled up. Was " .. oldlevel .. "  now " .. hist.me.level)
    hist.me.levels[hist.me.level] = {
        begin = GetTimeStamp(),
        time  = 0,		-- Accumulated time in Minutes
        Ach_Points = GetEarnedAchievementPoints(),
        deaths = 0
    }
    if hist.debug then
      d("Hist: Leveled:.. ")
          d(hist.me.level)
    end
	else  -- not "player"
		if hist.debug then
		d("Hist: Got Levelup Event, but not for me")
        d(unitTag)
		end
	end
end
local function gendertext()
	if (GetUnitGender("player") == GENDER_MALE)
	then return "M"
	end

	if (GetUnitGender("player") == GENDER_FEMALE)
	then return "F"
	end

	return "U"
end
local function setup_char()
		log("Set up: " .. hist.player )
		hist.SV.data[hist.player] = {}		-- initialise data for current char
		hist.me = hist.SV.data[hist.player]

		hist.me.Recorded = GetTimeStamp()
		hist.me.Class = GetUnitClass("player")
		hist.me.Race = GetUnitRace("player")
		hist.me.Gender = gendertext()
		hist.me.level = GetUnitLevel("player") + GetUnitVeteranRank("player")
		hist.me.Alliance = GetAllianceName(GetUnitAlliance("player"))
		hist.me.ach={}
		hist.me.levels = {}
		hist.me.levels[hist.me.level] = {
			begin = GetTimeStamp(),
			time  = 0,		-- Accumulated time in Minutes
			Ach_Points = GetEarnedAchievementPoints(),
			deaths = 0
		}  -- end of defaults
		load_history()
end

local function Dead()
	hist.me.levels[hist.me.level].deaths = hist.me.levels[hist.me.level].deaths +1
end
function hist.Initialise(_, addOnName)
	if (hist.name ~= addOnName) then return end

	-- find comupted time differnce.
	local now = GetTimeStamp()
	hist.datestr = GetDateStringFromTimestamp(now)
	hist.timestr = GetTimeString()
	hist.luatz_ts = luatz_esodate(hist.datestr .." " .. hist.timestr)
	hist.tz_offset = now - hist.luatz_ts

	hist.player = GetUnitName("player")
	local level = GetUnitLevel("player") + GetUnitVeteranRank("player")
    -- Load the saved variables
    hist.SV = ZO_SavedVars:NewAccountWide("History_SV", 1, nil, nil)
	if hist.SV.log == nil
	then hist.SV.log = {}
	end

	if (hist.SV.data == nil ) then
		hist.SV.data = {}
		log("hist.SV.data  created")
	end
	if (hist.SV.old == nil ) then
		hist.SV.old = {}
		log("hist.SV.old  created")
	end
	if hist.SV.data[hist.player] == nil
	then
		setup_char()
	else	-- data already there
		-- but is it for the same char?

		hist.me = hist.SV.data[hist.player]
		if hist.me.level == nil then		-- fix if doesn't exist
			hist.me.level = level
		end
		if hist.me.ach_updates ~= nil then
			hist.me.ach_updates = nil
		end

		    if hist.debug then
					log("Begin Duplicate tests, Saved  -- Calculated" )
					log("Alliance test: " .. hist.me.Alliance .. " -- " .. GetAllianceName(GetUnitAlliance("player")))
					log("Race test: " .. hist.me.Race .. " -- " .. GetUnitRace("player"))
					log("Class test: "  .. hist.me.Class .. " -- " .. GetUnitClass("player"))
					log("Gender test: " .. hist.me.Gender .. " -- " .. gendertext())
					log("Level Lower: " .. hist.me.level .. " -- " .. level)
			end
		if hist.me.Alliance  ~=  GetAllianceName(GetUnitAlliance("player")) or
			hist.me.Race ~= GetUnitRace("player") or
			hist.me.Class ~= GetUnitClass("player") or
			hist.me["Gender"] ~= gendertext() or
			hist.me.level > level
			then -- must be different with same name
			local now = GetTimeStamp()
			log("Duplicate Detected, moving to old")
			hist.SV.old[now] = {}	-- save old with timestamp
			hist.SV.old[now][hist.player] = {}
			hist.SV.old[now][hist.player] = hist.SV.data[hist.player]  -- Saved
			hist.SV.data[hist.player] = nil		-- Poof, gone
			setup_char()  -- setup defaults
			hist.SV.data[hist.player].OverWrite = true
		end
	end


	hist.me["LoginTime"] = GetTimeStamp()

	EVENT_MANAGER:RegisterForEvent(hist.name, EVENT_ACHIEVEMENT_AWARDED, Achievement)
	EVENT_MANAGER:RegisterForEvent(hist.name, EVENT_LEVEL_UPDATE, levelup)
	EVENT_MANAGER:RegisterForEvent(hist.name, EVENT_VETERAN_RANK_UPDATE, levelup)
	EVENT_MANAGER:RegisterForEvent(hist.name, EVENT_PLAYER_ACTIVATED, Activated)
	EVENT_MANAGER:RegisterForEvent(hist.name, EVENT_PLAYER_DEACTIVATED, Activated)
	EVENT_MANAGER:RegisterForEvent(hist.name, EVENT_PLAYER_DEAD, Dead)
	hist.initialised = true
end



SLASH_COMMANDS["/histload"] = load_history
SLASH_COMMANDS["/histfix"] = fix
SLASH_COMMANDS["/histclear"] = log_clear

EVENT_MANAGER:RegisterForEvent(hist.name, EVENT_ADD_ON_LOADED, hist.Initialise)