import json

from django.http import JsonResponse
from django.views import View

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

from productivity_bot.inbound_message_handlers import handle_inbound_message
from productivity_bot.message_users_helpers import send_reminder

from productivity_bot.models import ActiveLoops


# Corresponds to '/chatbot_event'
class ChatbotEvent(View):

	# Remove csrf protection from this endpoint
	@method_decorator(csrf_exempt)
	def dispatch(self, request, *args, **kwargs):
		return super(ChatbotEvent, self).dispatch(request, *args, **kwargs)

	def post(self, request):
		event = json.loads(request.body)

		if event['type'] == 'ADDED_TO_SPACE':
			response = ('Hi, my name is Productivity Bot! I\'m going to help '+
						'you keep track of your productivity. To start your '+
						'first working session, say "start"')
			return JsonResponse({'text': response})

		if event['type'] == 'MESSAGE':
			message_text = event['message']['text']
			user_id = event['user']['name']
			email = event['user']['email']
			space_name = event['space']['name']
			response = handle_inbound_message(message_text, user_id, space_name,
											  email)
			return JsonResponse({'text': response})

		return JsonResponse({'status': '404'})


class MessageUsers(View):

	# Remove csrf protection from this endpoint
	@method_decorator(csrf_exempt)
	def dispatch(self, request, *args, **kwargs):
		return super(MessageUsers, self).dispatch(request, *args, **kwargs)

  # uses crontabs
	def get(self, request):
		for active_loop in ActiveLoops.objects.all():
			send_reminder(active_loop.user.space_name)
		return JsonResponse({'status': '404'})
