local cf_img = {}

cf_img.triggers = {
  '(https?://img.ponywave.de)/(.*).html',
  '(https?://img.akamaru.de)/(.*).html'
}
cf_img.inline_triggers = cf_img.triggers

function cf_img:get_full_url(site, pic)
  local url = site..'/'..pic..'.html'
  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 full_url = string.match(res, "id=\"codedirect\" value%=\"(.-)\" onclick")
  return full_url
end

function cf_img:inline_callback(inline_query, config, matches)
  local site = matches[1]
  local pic = matches[2]
  local full_url = cf_img:get_full_url(site, pic)
  if not full_url then abort_inline_query(inline_query) return end
  
  local results
  
  if string.ends(full_url, '.gif') then
    results = '[{"type":"gif","id":"7778","gif_url":"'..full_url..'","thumb_url":"'..full_url..'"}]'
  else
    results = '[{"type":"photo","id":"7777","photo_url":"'..full_url..'","thumb_url":"'..full_url..'"}]'
  end
  utilities.answer_inline_query(inline_query, results, 3600, true)
end

function cf_img:action(msg, config, matches)
  local site = matches[1]
  local pic = matches[2]
  local full_url = cf_img:get_full_url(site, pic)
  if not full_url then
  	utilities.send_reply(msg, config.errors.connection)
	return
  end
  
  utilities.send_typing(msg.chat.id, 'upload_photo')
  local file = download_to_file(full_url)
  if string.ends(full_url, '.gif') then
    utilities.send_document(msg.chat.id, file, nil, msg.message_id)
  else
    utilities.send_photo(msg.chat.id, file, nil, msg.message_id)
  end
end

return cf_img