import threading
import cPickle
from array import array

from BitTorrent.Storage import Storage,FilePool
from BitTorrent.StorageWrapper import StorageWrapper

def finished():
	print "Finished\n"

def statusfunc(activity = None, fractionDone = 0):
	print "calling statusfunc\n"

def data_flunked(amount, index):
	print "calling data_flunked\n"

def errorfunc(level, text):
	print "calling error func\n"


# check_hashes need to be set to 1, so that it will try to load fast resume
# file. Because we don't have any resume file, so rplaces will be None, and
# then they will be initialized with UNALLOCATED (-2)
# If we don't do so, run-time error will happen.
if __name__ == '__main__': 
	config = {'enable_bad_libc_workaround': 0, 'check_hashes': 1, 'processid': 0, 'processes': 2,
'download_slice_size': 32, 'no_validate_piece': 1, 'piece_filename': '../piece' }
	myfiles = ['hello.txt']
	sizes = [1024]
	filepool = FilePool(1)
	storage = Storage(config, filepool, zip(myfiles, sizes), False)
	hashes = [1] * 16 
	doneflag = threading.Event()
	piecesize = 1024/16
	wrapper = StorageWrapper(storage, config, hashes, piecesize, finished, statusfunc, 
		doneflag, data_flunked, 'infohash', errorfunc, None)
# Now suppose the pieces come in different orders, say 15, 13, ..., 1, 14, ..., 0
# First need to request it
# What if I don't request it?
	index = 15
	(begin, length) = wrapper.new_request(index)
	assert begin==0 and length == 32
	(begin, length) = wrapper.new_request(index)
	assert begin==32 and length == 32
	strdata = '15' * 16
	result = wrapper.piece_came_in(index, 0, strdata)
# This should be True, meaning we validate and save the slice successfully 
	assert result==True
	result = wrapper.piece_came_in(index, 32, strdata)
	assert result==True
	assert wrapper.do_I_have(index)==True
	assert wrapper.do_I_have(index-1)==False
# I should request first
	index=14
	strdata = str(index) * 16
	(begin, length) = wrapper.new_request(index)
	(begin, length) = wrapper.new_request(index)
	result = wrapper.piece_came_in(index, 0, strdata)
	assert result==True
	assert wrapper.do_I_have(index)==False
	result = wrapper.piece_came_in(index, 32, strdata)
	assert result==True
	assert wrapper.do_I_have(index)
# Now [8-14), i.e., 8, 9, 10, ..., 13
	for i in range(0,14):
		(begin, length) = wrapper.new_request(i)
		(begin, length) = wrapper.new_request(i)
		strdata = ("%02d" %(i)) * 16
		result = wrapper.piece_came_in(i, 0, strdata)
		result = wrapper.piece_came_in(i, 32, strdata)
		print wrapper.places
		assert wrapper.do_I_have(i)
        print "Download done"
	print wrapper.places
	print wrapper.rplaces
# Please check hello.txt to see the file's content. The text should be in order.
	#h  = open('places.txt', 'w')
	#wrapper.places.tofile(h)
	#h.close()
	h  = open('places.txt', 'r')
	#myplaces = array('h', array.fromfile(h, 16))
	myplaces = array('h')
	myplaces.fromfile(h, 16)
	h.close()
	print myplaces
	

