# -*- coding: utf-8 -*-
#######################
# WARNING
# Running this code sample will cost you Browshot credits
#######################

from browshot import BrowshotClient
import time

browshot = BrowshotClient('my_api_key')

screenshot = browshot.screenshot_create('http://www.google.com/', { 'instance_id': 12, 'size': 'page' }) # all default parameters, instance_id = 12 (free)

# If the screenshot is already in cache, it could be finished already. Otherwise, wait longer
while screenshot['status'] != 'finished' and  screenshot['status'] != 'error':
  print "Wait...\n"
  time.sleep(10)
  screenshot = browshot.screenshot_info(screenshot['id'])


# screenshot is done: finished (sucessful) or error (failed)
if screenshot['status'] == 'error':
  print "Screenshot failed: %s\n" % screenshot['error'] # display the reason for the error
else: # request the thumbnail
  image = browshot.screenshot_thumbnail(screenshot['id'])
  
  # save the screenshot
  fp = open("browshot.png", mode='wb')
  fp.write(image)
  fp.close()


# you can combine several calls into 1: screenshot_create + screenshot_host
screenshot = browshot.screenshot_create('https://browshot.com/',
{
	'instance_id': 24, # premium
	'screen_width': 1600, # wide screen
	'screen_height': 1200, 
	'size': 'page', # full page
	'delay': 25, # greater delay if the page si very longer
	'hosting': 's3', # make sure you have set up your S3 bucket with the right ACL
	'hosting_bucket': 'my_bucket',
	'hosting_file': 'myfile.png', # can be omitted
	'hosting_width': 400, # thumbnail 400px wide
})


# Make multiple screenshots of the same page (loaded once)
screenshot = browshot.screenshot_create('https://youtube.com/', 
{
	'instance_id': 24, # premium
	'shots': 5 ,          # 5 screenshots
	'shot_interval': 10, # every 10 seconds
	'screen_width': 1280,
	'screen_height': 1024,
})

time.sleep(60)

screenshot = browshot.screenshot_info(screenshot['id'])
if screenshot['status'] == 'finished':
  # download the 5 screenshots
  for i in range (1, 5):
    browshot.screenshot_thumbnail_file(screenshot['id'], "%d.png" % i, { 'height': 600, 'shot': i })


# Host the screenshot on S3
screenshot = browshot.screenshot_create('https://youtube.com/',
{
	'instance_id': 24, # premium
	'screen_width': 1280,
	'screen_height': 1024,
	'hosting': 's3',
	'hosting_bucket': 'my_bucket',
	'hosting_file': 'youtube.png',
	'hosting_width': 600 # thumbnail
})

time.sleep(60)

screenshot = browshot.screenshot_info(screenshot['id'])
if screenshot['status'] == 'finished':
  # The screenshot may not be hosted yet
  if 'hosted_url' in screenshot and screenshot['hosted_url'] != '':
    print "\nScreenshot hosted at %s\n" % screenshot['hosted_url']
