from django.core.management.base import BaseCommand, CommandError
from Client.models import Bookings
from CommonApp.utils import sendMail, CreateNotification
from datetime import datetime

class Command(BaseCommand):
	help = 'Send reminder to clients and coaches, 15 minute before session gets started'

	def add_arguments(self, parser):
		# parser.add_argument('poll_ids', nargs='+', type=int)

	# Named (optional) arguments
		parser.add_argument(
			'--reminder',
			action='store_true',
			help='Send reminder to clients and coaches 15 minute before session gets started',
		)

	def handle(self, *args, **options):
		bookings = Bookings.objects.filter(session_date=datetime.now().date(), cancelled_at__isnull=True)
		# raise Exception(bookings)
		for booking in bookings:
			# try:
			# 	poll = Poll.objects.get(pk=poll_id)
			# except Poll.DoesNotExist:
			# 	raise CommandError('Poll "%s" does not exist' % poll_id)
			# try:
			booking_date = datetime.strptime(booking.session_date+' '+booking.session_time, '%Y-%m-%d %H:%M')
			diff = int(((booking_date-datetime.now()).total_seconds())/60)
			# raise Exception(diff)
			if diff <= 15 and diff > 0:
				noti_text = 'Your session with ('+booking.user.userprofile.name+') begins in 15 minutes at '+booking.session_time	#coach
				CreateNotification('booking', booking.id, booking.user_id, booking.coach_id, 'n', noti_text, booking.category_id)

				noti_text = 'Your session with ('+booking.coach.userprofile.name+') begins in 15 minutes at '+booking.session_time
				CreateNotification('booking', booking.id, booking.coach_id, booking.user_id, 'n', noti_text, booking.category_id)

				# sending mail to coach
				subject = 'Hapsmiths Booking Reminder'
				content = booking
				template = "emails/booking-reminder-coach.html"
				sendMail(subject, content, [booking.coach.email], template)
				template = "emails/booking-reminder-client.html"
				sendMail(subject, content, [booking.user.email], template)
			# except:
			# 	raise CommandError('Booking id "%s" can not be updated' % booking.id)

		self.stdout.write(self.style.SUCCESS('Successfully sent email and notfication'))