local mfc = {}

function mfc:init(config)
  mfc.triggers = {
	"^/[Mm][Ff][Cc] (.+)$",
	"myfigurecollection.net/user/(.+)$",
	"myfigurecollection.net/collection/(.+)$"
  }
  mfc.doc = [[*
]]..config.cmd_pat..[[mfc* _<User>_: Zeigt den zuletzt hinzugefügten Artikel eines MyFigureCollection-Users
]]
end

mfc.command = 'mfc <User>'

local makeOurDate = function(dateString)
  local pattern = "(%d+)%-(%d+)%-(%d+)"
  local year, month, day = dateString:match(pattern)
  if day == "00" then
  return month..'.'..year
  else
  return day..'.'..month..'.'..year
  end
end

function mfc:get_infos(user)
  local url = 'http://myfigurecollection.net/api.php?type=json&mode=collection&username='..user
  local res, code  = http.request(url)
  if code ~= 200 then return nil end
  local data = json.decode(res).collection.owned
  if not data then return nil end
 
  local title = data.item[1].data.name
  local owned = data.num_items
  local profile_url = 'http://de.myfigurecollection.net/collection/'..user
  local art = data.item[1].root.name
  local category = data.item[1].category.name
  local date = makeOurDate(data.item[1].data.release_date)
  local price = '¥'..data.item[1].data.price
  local url = 'http://de.myfigurecollection.net/item/'..data.item[1].data.id
  
  local text = 'Letzter Artikel aus <b>'..user..'\'s</b> <a href="'..profile_url..'">Sammlung</a> ('..owned..' Artikel):\n<a href="'..url..'">'..title..'</a>\nArt: '..art..' ('..category..')\n<i>Erschien am '..date..' für '..price..'</i>'
 
  return text
end

function mfc:action(msg, config, matches)
  local user = matches[1]
  local text = mfc:get_infos(user)
  if not text then
    utilities.send_reply(msg, config.errors.results)
	return
  end
  utilities.send_reply(msg, text, 'HTML')
end

return mfc