from facebook import *
from database import *
import dateutil.parser
import sys

class Collector:
	class statistics:
		messages_collected = 	0
		threads_updated	=		0
		threads_skipped	=		0

	def __init__ (self, access_token):
		self.facebook = Facebook(access_token)
		self.database = Database()

	def collect (self):
		print('[Threads] Collection started')
		threads = self.collect_threads(max_pages=0)
		print("[Threads] Collected done, %i threads collected" % (threads.__len__()))

		print('[Threads] Parsing and processing threads...')
		threads = self.database.parse_threads(threads)

		print('[Messages] Collecting...')
		for thread in threads:
			if thread:
				self.statistics.threads_updated += 1
				print thread
				
				thread['max_pages'] = 0

				collected_count = messages = self.collect_messages(**thread)
				self.statistics.messages_collected += collected_count
				print("[Messages] Collected %i messages in this thread" % (collected_count))

				self.database.set_direction(thread['thread_id'], 'forwards')
			else:
				self.statistics.threads_skipped += 1
		print('[Messages] Collection done!')

		print ("[Done] Skipped %i threads, updated %i threads and collected %i messages" % (
			self.statistics.threads_skipped,
			self.statistics.threads_updated,
			self.statistics.messages_collected
		))

		return None

	def collect_threads (self, thread_id=None, date=None, page=1, max_pages=0):
		threads = self.facebook.query_threads(thread_id, date)

		print("[Threads] Page %i, collected %i threads" % (page, threads.__len__()))

		if threads.__len__() is 0 or page is max_pages or threads.__len__() < self.facebook.api_thread_limit:
			return threads
		else:
			last_thread = threads[-1]

			return threads + self.collect_threads(
				thread_id=last_thread['id'], 
				date=dateutil.parser.parse(last_thread['updated_time']),
				page=page + 1,
				max_pages=max_pages
			)

	def collect_messages (self, thread_id, direction, message_id=None, date=None, page=1, max_pages=0, collected_count=0):
		if direction is 'backwards':
			messages = self.facebook.query_messages_backwards(thread_id, message_id, date)
		elif direction is 'forwards':
			messages = self.facebook.query_messages_forwards(thread_id, message_id, date)
		else:
			# Terminate the script with a proper error message
			sys.exit("Error, no direction specified")

		print("[Messages] Page %i, collected %i messages" % (page, messages.__len__()))

		collected_count += messages.__len__()
		self.database.insert_messages(messages, thread_id)

		if messages.__len__() is 0 or page is max_pages or messages.__len__() < self.facebook.api_message_limit:
			return collected_count
		else:
			if direction is 'backwards':
				# Backwards
				attack_page = messages[-1]
			else:
				# Forwards
				attack_page = messages[0]

			return self.collect_messages(
				thread_id=thread_id,
				direction=direction,
				message_id=attack_page['id'],
				date=dateutil.parser.parse(attack_page['created_time']),
				page=page + 1,
				max_pages=max_pages,
				collected_count=collected_count
			)