local wordpress_recent_post = {}

wordpress_recent_post.triggers = {
  "^/([Aa][Kk][Aa]) (.+)$",
  "^/([Tt][Hh][Cc]) (.+)$",
  "^/([Pp][Ww]) (.+)$",
  "^/([Aa][Kk][Aa])$",
  "^/([Tt][Hh][Cc])$",
  "^/([Pp][Ww])$"
}

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

function wordpress_recent_post:get_full_url(blog, tag)
  if tag then
    url = blog..'/?json=get_search_results&search='..tag
  else
    url = blog..'/?json=get_recent_posts'
  end
  local doer = http
  if url:match('^https') then
	doer = https
  end
  local res, code  = doer.request(url)
  if code ~= 200 then return nil end
  local data = json.decode(res).posts[1]
  if not data then return 'NOTFOUND' end
 
  local title = unescape(data.title)
  local from = unescape(data.author.name)
  local posted_at = makeOurDate(data.date)
  local content = data.excerpt:match('<p>(.*)<span')
  if not content then
    content = data.excerpt:match('<p>(.*)</p>')
  end
  if not content then
    content = ""
  else
    content = '\n'..unescape(content)..'...'
  end
  local url = data.url
  if data.thumbnail then
    image_url = data.thumbnail
  else
    image_url = nil
  end
  
  local text = '<b>'..title..'</b>\n<i>'..from..' am '..posted_at..'</i>'..content..'\n<a href="'..url..'">Beitrag aufrufen</a>'
  return text, image_url
end

function wordpress_recent_post:action(msg, config, matches)
  local blog = matches[1]
  if blog:match('[Aa][Kk][Aa]') then
    blog = 'http://akamaru.de'
  elseif blog:match('[Pp][Ww]') then
    blog = 'https://ponywave.de'
  elseif blog:match('[Tt][Hh][Cc]') then
    blog = 'http://homebrew.cloud'
  end
  local text, image_url = wordpress_recent_post:get_full_url(blog, matches[2])
  if not text then
  	utilities.send_reply(msg, config.errors.connection)
	return
  elseif text == 'NOTFOUND' then
  	utilities.send_reply(msg, config.errors.results)
	return
  end
  
  if image_url then
    utilities.send_typing(msg.chat.id, 'upload_photo')
    local file = download_to_file(image_url)
    utilities.send_photo(msg.chat.id, file, nil, msg.message_id)
  end
  utilities.send_reply(msg, text, 'HTML')
end

return wordpress_recent_post