#!/usr/bin/env python
__version__ = "0.2b"
__author__ = "age"
__date__ = "02006-04-25"

import urllib
from optparse import OptionParser

class WKNCharts:
	'''fetches images from stocks'''
	def __init__(self):
		self.wkn_dict = {}
		self.times = [300]

	def readwkndictfromfile(self, filename):
		'''reads lines like "wkn name\n" from a file and fills a dictionary'''
		wknfile = open(filename,"r")
		for line in wknfile:
			'remove CRLF and split the line in two parts on spacer'
			tmp = line.strip("\n").split(" ")
			if tmp[0] and tmp[1]: self.wkn_dict[tmp[0]] = tmp[1]
		wknfile.close()
	
	def readwkndictfromstring(self, wknstring):
		'''takes the given string into a "wkn name" dictionary'''
		tmp2 = wknstring.splitlines()
		print len(tmp2)
		for i in tmp2:
			tmp = i.split()
			if tmp[0] and tmp[1]: self.wkn_dict[tmp[0]] = tmp[1]

	def getchart(self, wkn, time, width=400, height=240):
		'''fetches the images via http'''
		host = "http://gfx.finanztreff.de/charts/cc_gatrixx.gfx?"
		params = urllib.urlencode({
			'string':wkn,
			'b':width,
			'h':height,
			'out':"png",
			'zeit':time,
			'typ':0,
			'boerse':1,
			'land':276,
			'seite':"kurse",
			'herkunft':123
			})
		#print "ich hole jetzt \"%s\" %i:" % (self.wkn_dict[wkn], time)
		#print host + params
		self.gui.add_log("%s %s" % (host, params))
		try:
			'''
			f = urllib.urlopen(host + params)
			png = open("images/"+self.wkn_dict[wkn]+str(time)+".png", "w")
			png.write(f.read())
			png.close()
			'''
			import time
			time.sleep(2)
		except IOError, e:
			print e

	def set_times(self, times):
		self.times = times

	def getallcharts(self, gui) :
		self.gui = gui
		for wkn in self.wkn_dict.keys():
			self.gui.add_log("hole: %s (%s)" % (self.wkn_dict[wkn], wkn))
			for time in self.times:
				self.getchart(wkn, time)
		print "Download fertig"
		return
		

if __name__ == "__main__":
	parser = OptionParser()
	parser.add_option("-f", "--file", dest="filename",
                  help="read WKNS from FILE", metavar="FILE")
	(options, args) = parser.parse_args()

	wkn = WKNCharts()
	wkn.readwkndictfromfile(options.filename)
	#for i in wkn.wkn_dict.keys():
		#print "%s \t %s" % (i, wkn.wkn_dict[i])
	wkn.getallcharts()
	#wkn.addwkn(wkn, name)
	#wkn.delwkn(wkn)