--Licence: No restriction and no responsibility
dateformat = "%d/%m, %H:%M"

require( "iuplua" )
require( "iupluacontrols" )

dofile "C:/iup/prog/ResearchTimer.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 i =0 k =0

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

local allcraft = ResearchTimer["Default"][myaccount]["$AccountWide"]["Craft"]

-- print (dump (allcraft))
local summary = {} names = {}
 for char, _ in pairs(allcraft) do
        if allcraft[char]["shortest"] ~= nil  -- Some chars may have incorrect data. Just Skip.
		then
--		print (allcraft[char]["shortest"]);
			summary[char] = {}
			for craft, _ in pairs (allcraft[char]) do
				summary[char][craft] = {}
				summary[char][craft]["Finished"] = 0
			end
		table.insert (names, char)
		end
	end
lines=  #names

table.sort(names, function (a,b) return allcraft[a].shortest < allcraft[b].shortest end)


mat = iup.matrix {numcol=3, numlin=lines, numlin_visible = lines, numcol_visible=3, widthdef=150,heightdef=40}
mat.resizematrix = "YES"
mat.hidefocus = "YES"
mat.multiline = "YES"
mat.readonly = "YES"

mat:setcell(0,0,"Character")
mat:setcell(0,1,"Blacksmithing")
mat:setcell(0,2,"Clothing")
mat:setcell(0,3,"Woodworking")

for k, char in ipairs(names) do
mat:setcell(k,0,char)

  for  thiscraft = 0,2  do  -- cant use ipairs as it starts from 0. can't use pairs, has "shortest" as key
	  local itemstr = "" itempadded = ""
	  for thisdoing, thisitem in pairs(allcraft[char][thiscraft].doing) do
		--print (thisitem.Item_name)
		itempadded = thisitem.Item_name .. "\\" .. thisitem.Trait_name .. string.rep("-", 40)
		itempadded = string.sub(itempadded,1,26)
		itemstr = itemstr .. itempadded    .. "  " .. os.date(dateformat,thisitem.EndTimeStamp) .. "\n"
	  end

	  mat:setcell(k,thiscraft+1, string.sub(itemstr, 1, string.len(itemstr)-1))  -- cut trailing newline
  end
end


dlg = iup.dialog{iup.vbox{mat; margin="10x10"}}

dlg:showxy(iup.CENTER, iup.CENTER)
dlg.title="Research"

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