#!/usr/bin/env python

import requests, bs4

from PIL import Image, ImageTk
from StringIO import StringIO
from Tkinter import Tk, Label, Entry
from bs4 import BeautifulSoup


def get_text(e):
	global root, captcha_code

	captcha_code = inbox.get()
	root.destroy()


if __name__ == '__main__':
	sess = requests.Session()
	sess.headers.update({'User-Agent': 'Mozilla/5.0'})

	username='sweethabbi'

	thing = sess.get("https://retroslist.com/vote/" + username).text.encode('utf-8')
	soup = BeautifulSoup(thing)
	captcha_link = soup.find("img", attrs={"class": "img-polaroid"})["data-cfsrc"]

	root = Tk()
	image = StringIO(sess.get(captcha_link).content)
	tkimg = ImageTk.PhotoImage(Image.open(image))

	label = Label(image=tkimg)
	label.pack()

	inbox = Entry(root)
	inbox.bind('<Return>', get_text)
	inbox.pack()

	label.image = tkimg
	root.mainloop()
	r = sess.post('https://retroslist.com/vote/' + username, data={'captcha': captcha_code, 'vote': 'Vote'})
	print r.text
	if r.status_code != 302:
		print('Failed. %s' % r.status_code)
	else:
		print('Voted.')