-- This is a proprietary plugin, property of Andreas Bielawski, (c) 2015 <andi (dot) b (at) outlook (dot) de>
-- DO NOT USE WITHOUT PERMISSION

do

local BASE_URL = 'http://api.page2images.com/'
local restkey = cred_data.page2images_restkey

function get_scrot_data (scrot_url)
  local url = BASE_URL..'/restfullink?p2i_url='..scrot_url..'&p2i_key='..restkey..'&p2i_imageformat=png&p2i_quality=85&p2i_size=1366x768'
  local res,code  = http.request(url)
  if code ~= 200 then return "HTTP-FEHLER" end
  local data = json:decode(res)
  return data
end

function send_scrot_data(data, receiver)
  if data.status == "processing" then
    print('Screenshot wird erstellt. Ungefähre Dauer: '..data.estimated_need_time..' Sekunden')
  end
  
  while data.status == "processing" do
    sleep(5)
	data = get_scrot_data(scrot_url)
	if data.estimated_need_time ~= nil then
	  print('Noch '..data.estimated_need_time..' Sekunden')
	end
  end
  
  if data.status == "error" then
    text = data.ori_url..' konnte nicht fotografiert werden, weil der Fehler "'..data.msg..'" '..data.errno..' auftrat.'
	send_msg(receiver, text, ok_cb, false)
  end
  
  if data.status == "finished" then
    left_calls = data.left_calls
    text = data.ori_url..' wurde fotografiert. Verbleibende API-Calls: '..left_calls
    image_url = data.image_url
    cb_extra = {
      receiver=receiver,
      url=image_url
    }
	send_msg(receiver, text, send_photo_from_url_callback, cb_extra)
  end
end

function run(msg, matches)
  scrot_url = matches[1]
  local data = get_scrot_data(scrot_url)
  local receiver = get_receiver(msg)
  send_scrot_data(data, receiver)
end

return {
  description = "Sendet Webseiten-Screenshot.", 
  usage = {"#scrot2 [URL]"},
  patterns = {"^#scrot2 (https?://[%w-_%.%?%.:/%+=&]+)"},
  run = run 
}

end
