#!/usr/bin/env python2
import core
import dropbox

class wrapper(core.framework):
	def __init__(self, auth=True, **kwargs):
		if ('APP_KEY' not in kwargs or 'APP_SECRET' not in kwargs):
			print("This class requires APP_KEY and APP_SECRET parameters")
			return None

		defaults = { 
			'chunk_size' : core.constant(64 * 1024),
			'service'    : 'dropbox',
			'instance_name' : 'default',
			'fragment_expiry' : 28 * (24 * 60 * 60)
		}

		core.framework.__init__(self, defaults, **kwargs)
		
		self.auth()


	def reassemble_generator(self, internal_handle):
		client = dropbox.client.DropboxClient(self.session)

		for frag, size in self.db_hook.get_file_fragments(internal_handle):
			print ("chunk '%s': size: '%s'" % (frag, size))
			yield client.get_file(internal_handle, frag)

	def auth(self):
		
		self.session = dropbox.session.DropboxSession(self.APP_KEY, self.APP_SECRET, 'app_folder')

		# TODO: Fix this. it's not properly resolving the 'execute' property of 'self.handle.cursor'.
		# (key, secret) = self.db_hook.get_access_token(self.service, self.instance_name)
		
		creds = self.db_hook.handle.execute("SELECT key, secret FROM access_tokens WHERE service = ? AND instance_name = ?", (self.service, self.instance_name)).fetchone()

		if (creds != None):
			(key, secret) = creds
			self.session.set_token(key, secret)

		else:
			request_token = self.session.obtain_request_token()
		
			print ("Please visit the following url to authorize this access.")
			print (self.session.build_authorize_url(request_token))
			print ("Press any key to continue.")

			raw_input()
		
			access_token = self.session.obtain_access_token(request_token)
			self.db_hook.store_oauth_token(self.service, self.instance_name, access_token.key, access_token.secret)


	def get(self, hook_name, output_file = None):
		self.reassemble(hook_name, output_file)

	def put(self, filename):
		client = dropbox.client.DropboxClient(self.session)
		hook_name = core.git_style_hash(filename)
		responses = []
		
		if (self.db_hook.exists(hook_name)):
			print ("File already exists. Skipping fragment gen/registration.")

		else:
			for chunk in self.fragment(filename):
				f = open(chunk)
				while True:
					try:
						response = client.put_file(hook_name, f, True)
						break
					except:
						print ("FAILED to put '%s', retrying." % hook_name)
				f.close()
				responses += [response]

			self.register_file(filename, hook_name, responses)
	
		return hook_name

	def list_files(self, fileName):
		return self.db_hook.get_files(service=self.service, instance_name = self.instance_name, path=fileName)

