from django.db import models

from django.conf import settings

import urllib
import pycurl
import StringIO
import os
import re
import time

# Create your models here.

# Some usefull constants
LOGIN_URL = 'https://ssl.rapidshare.com/cgi-bin/premiumzone.cgi'
UPLOAD_TO = 'cookies'

class Account(models.Model):
	"""
		Represents a RapidShare account
	"""

	login = models.CharField(maxlength=25)
	password = models.CharField(maxlength=25)
	#cookie_jar = models.FileField(blank=True, null=True, upload_to="cookies", maxlength=250)
	cookie_jar = models.FileField(blank=True, null=True, upload_to=UPLOAD_TO)
	valid_date = models.DateField(blank=True, null=True)
	last_five_days = models.IntegerField(blank=True, null=True)
	status = models.IntegerField(blank=True, null=True, default = -1)

	#Some constants
	STATUS_NOT_EXISTS = -1
	STATUS_INACTIVE = 0
	STATUS_ACTIVE = 1

	#Regular expresions to fetch data
	DOWNLOADED_REGEXP = re.compile("""<td>5 days Traffic:</td><td align=right style="padding-right:20px;"><b>(.\d+) MB</b>""")
	PREMIUMPOINTS_REGEXP = re.compile("""<td>RapidPoints:</td><td style="padding-right:20px;"><b>(.\d+)</b>""")
	USEDSTORAGE_REGEXP = re.compile("""<td>Used storage:</td><td align=right style="padding-right:20px;"><b>((.\d+)(\.(.\d+))?) MB</b>""")
	EXPIRATION_REGEXP = re.compile("""<td>Expiration date:</td><td style="padding-right:20px;"><b>(.+)</b></td>""")

	class Admin:
		list_display = ('login',)

	def clear_cookie_jar(self):
		"""
			Erase the cookie_jar
		"""
		if self.cookie_jar and os.path.isfile(self.get_cookie_jar_filename()):
			os.unlink(self.get_cookie_jar_filename())
			self.cookie_jar = None

	def authenticate(self):
		"""
			Try to authenticate in RapidShare with params supplied.

			If authentication is succesfull, the cookie jar containing
			the magic info to download data will be saved to the cookies
			directory.

			The result of this operation is the account status.

		"""
		if self.login is None and self.password is None:
			return (False, "Please initialize this object")

		self.cookie_jar = "%s/%s/cookie_jar_%s.txt" % (settings.MEDIA_ROOT, UPLOAD_TO , self.login)

		#Perform the http post to the login page
		htmlFile = StringIO.StringIO()
		
		curl = pycurl.Curl()
		#Build the form data
		login_form = {'login': self.login, 'password': self.password}
		login_form_data = urllib.urlencode(login_form)

		#Set petition options
		curl.setopt(pycurl.COOKIEJAR, self.cookie_jar)
		curl.setopt(pycurl.POSTFIELDS, login_form_data)
		curl.setopt(pycurl.URL, LOGIN_URL)
		curl.setopt(pycurl.WRITEFUNCTION, htmlFile.write)


		#Now post
		curl.perform()
		html = htmlFile.getvalue()
		htmlFile.close()
		curl.close()

		#Now perform some basic checks against the html code
		if html.find("This Account expired on") <> -1:
			self.status = Account.STATUS_INACTIVE
		elif html.find("Premium-Account not found") <> -1:
        		self.status = Account.STATUS_NOT_EXISTS	
		else:
        		self.status = Account.STATUS_ACTIVE	
		#Now check the response

		#Extract information
		self.__extract_info__(html)
		
		self.save()
		return self.status

	def __extract_info__(self, html):
		"""
			Extract additional information from RS user home page
		"""
		#How much downloaded data?
		downloaded = int(Account.DOWNLOADED_REGEXP.findall(html)[0])
		
		#Premium points
		premium_points = int(Account.PREMIUMPOINTS_REGEXP.findall(html)[0])

		#Used storage
		#Refine this regexp
		try:
			used_storage = float(Account.USEDSTORAGE_REGEXP.findall(html)[0][0])
		except:
			used_storage = 0

		#Expiration date
		expiration_str = Account.EXPIRATION_REGEXP.findall(html)[0]
		#Now get a real date from that string
		pattern = """%a, %d. %b %Y"""
		expiration_date = int(time.mktime(time.strptime(expiration_str,
					pattern)))

		print "%d MB downloaded in five days" % downloaded
		print "%d premium points" % premium_points
		print "%.2f MB stored" % used_storage
		print "Expiration date: %s" % time.strftime("%d-%m-%Y", time.localtime(expiration_date))
