# from channels import Group


# def ws_connect(message):
#     Group('users').add(message.reply_channel)


# def ws_disconnect(message):
#     Group('users').discard(message.reply_channel)   



from channels.generic.websocket import AsyncWebsocketConsumer
from channels.consumer import AsyncConsumer
import json
from .models import Chat, Notifications
from Driver.models import DriverModel, DriverCoordinates, DriverJob
from asgiref.sync import async_to_sync
from Customer.commonfunctions import sendfcmnotification
        
from channels.exceptions import StopConsumer # from people reviews
from channels.db import database_sync_to_async

class DriverCoordinatesCustomerEndConsumer(AsyncConsumer):
	groups = ["broadcast"]

	async def websocket_connect(self, event):
		print('\n'*4)
		print('in DriverCoordinatesCustomerEndConsumer - connect')
		print('\n'*4)
		
		userrole = self.scope['url_route']['kwargs']['userrole']
		userid = self.scope['url_route']['kwargs']['userid']
		if userrole == 'driver':
			self.group_name = str(userrole) + '_' + str(userid)
		else:
			self.group_name = str(userrole)
		print('group_name = ', self.group_name)

		await self.channel_layer.group_add(
	        self.group_name,
	        self.channel_name
        )
		
		await self.send({
			'type':'websocket.accept'
			})


	async def new_message(self,event):
		print('\n'*10)
		print(' coordinates - new_message \n\n\n')
		print(event)
		print('\n'*10)
		try:
			await self.send({
				"type":"websocket.send",
				"text":event['text']
			})
				
		except Exception as e:
			print(e)
			pass



	async def websocket_receive(self, event):
		# Called with either text_data or bytes_data for each frame
		print('\n'*4)
		print('in DriverCoordinatesConsumer - receive')
		print('\n'*4)
		print(event['text'])
		try:
			if event['text'] == 'get coordinates':
				driverid = self.scope['url_route']['kwargs']['userid']
				driver_obj = DriverModel.objects.filter(id  = driverid).first()
				if driver_obj:
					driverjob_obj = DriverJob.objects.filter(customerjob = customerjob_obj).first()
					if driverjob_obj:
						if driverjob_obj.jobstarted:
							parcelpicked = True
					drivercoordinates_obj = DriverCoordinates.objects.filter(driver = driver_obj).first()
					if drivercoordinates_obj:
						drivercoordinates_data = {}
					
						drivercoordinates_data.update({
							'driverid': driver_obj.id,
							'latitude': drivercoordinates_obj.latitude,
							'longitude': drivercoordinates_obj.longitude,
							})
						print(drivercoordinates_data)
						# if 'driver' in self.group_name:
						# 	othergroup_name = 'admin_1'
						# else:
						# 	othergroup_name = 'driver' + '_' +str(drivercoordinates_data['driverid'])
						await self.channel_layer.group_send(
							self.group_name,
							{
								"type":"new_message",
								"text":json.dumps(drivercoordinates_data)
							}
						)
								
			else:
				b = json.loads(event['text'])
				print(b)
				# for b in a:
				try:
					print(b)
					# print(type(b))
					latitude_val = b['latitude']
					longitude_val = b['longitude']
					userrole = self.scope['url_route']['kwargs']['userrole']
					if 'driver' in userrole:
						driverid = self.scope['url_route']['kwargs']['userid']
						driver_obj = DriverModel.objects.filter(id  = driverid).first()
						if driver_obj:
							drivercoordinates_obj = DriverCoordinates.objects.filter(driver = driver_obj).first()
							if drivercoordinates_obj:
								drivercoordinates_obj.latitude = latitude_val
								drivercoordinates_obj.longitude = longitude_val
								drivercoordinates_obj.save()
								print('coordinates updated')
							else:
								DriverCoordinates.objects.create(user_id = driver_obj.user.id, driver = driver_obj, latitude = latitude_val, longitude = longitude_val)
								print('coordinates obj created')
							# return JsonResponse({'status_code': 200, 'status_message': 'success',})
						else:
							pass
							# return JsonResponse({'status_code': 400, 'status_message': 'User not logged in'})
				
				except Exception as e:
					print('driver get coordinates')

					driverid = self.scope['url_route']['kwargs']['userid']
					driver_obj = DriverModel.objects.filter(id  = driverid).first()
					if driver_obj:
						customerjobid_val = b['customerjobid']
						parcelpicked = False
						driverjob_obj = DriverJob.objects.filter(customerjob_id = customerjobid_val).first()
						if driverjob_obj:
							if driverjob_obj.jobstarted:
								parcelpicked = True
						drivercoordinates_obj = DriverCoordinates.objects.filter(driver = driver_obj).first()
						if drivercoordinates_obj:
							drivercoordinates_data = {}
						
							drivercoordinates_data.update({
								'driverid': driver_obj.id,
								'latitude': drivercoordinates_obj.latitude,
								'longitude': drivercoordinates_obj.longitude,
								})
							print(drivercoordinates_data)
							# if 'driver' in self.group_name:
							# 	othergroup_name = 'admin_1'
							# else:
							# 	othergroup_name = 'driver' + '_' +str(drivercoordinates_data['driverid'])
							await self.channel_layer.group_send(
								self.group_name,
								{
									"type":"new_message",
									"text":json.dumps(drivercoordinates_data)
								}
							)
				
		except Exception as e:
			print(e)			

		# await self.send(text_data="Hello world!")
		
	async def websocket_disconnect(self, close_code):
		print('\n'*4)
		print('in DriverCoordinatesConsumer - disconnect')
		print('\n'*4)
		# Called when the socket closes
		await self.channel_layer.group_discard(
			'admin_1',
			self.channel_name
			)
		try:
			raise StopConsumer() # this one deals with warnings
		except Exception as e:
			print(e)



class DriverCoordinatesConsumer(AsyncConsumer):
	groups = ["broadcast"]

	async def websocket_connect(self, event):
		print('\n'*4)
		print('in DriverCoordinatesConsumer - connect')
		print('\n'*4)
		
		userrole = self.scope['url_route']['kwargs']['userrole']
		userid = self.scope['url_route']['kwargs']['userid']
		if userrole == 'driver':
			self.group_name = str(userrole) + '_' + str(userid)
		else:
			self.group_name = str(userrole)
		print('group_name = ', self.group_name)

		await self.channel_layer.group_add(
	        self.group_name,
	        self.channel_name
        )
		
		await self.send({
			'type':'websocket.accept'
			})


	async def new_message(self,event):
		print('\n'*10)
		print(' coordinates - new_message \n\n\n')
		print(event)
		print('\n'*10)
		try:
			await self.send({
				"type":"websocket.send",
				"text":event['text']
			})
				
		except Exception as e:
			print(e)
			pass



	async def websocket_receive(self, event):
		# Called with either text_data or bytes_data for each frame
		print('\n'*4)
		print('in DriverCoordinatesConsumer - receive')
		print('\n'*4)
		print(event['text'])
		try:
			if event['text'] == 'get coordinates':
				driverid = self.scope['url_route']['kwargs']['userid']
				driver_obj = DriverModel.objects.filter(id  = driverid).first()
				if driver_obj:
					driverjob_obj = DriverJob.objects.filter(customerjob = customerjob_obj).first()
					if driverjob_obj:
						if driverjob_obj.jobstarted:
							parcelpicked = True
					drivercoordinates_obj = DriverCoordinates.objects.filter(driver = driver_obj).first()
					if drivercoordinates_obj:
						drivercoordinates_data = {}
					
						drivercoordinates_data.update({
							'driverid': driver_obj.id,
							'latitude': drivercoordinates_obj.latitude,
							'longitude': drivercoordinates_obj.longitude,
							})
						print(drivercoordinates_data)
						# if 'driver' in self.group_name:
						# 	othergroup_name = 'admin_1'
						# else:
						# 	othergroup_name = 'driver' + '_' +str(drivercoordinates_data['driverid'])
						await self.channel_layer.group_send(
							self.group_name,
							{
								"type":"new_message",
								"text":json.dumps(drivercoordinates_data)
							}
						)
								
			else:
				b = json.loads(event['text'])
				print(b)
				# for b in a:
				try:
					print(b)
					# print(type(b))
					latitude_val = b['latitude']
					longitude_val = b['longitude']
					userrole = self.scope['url_route']['kwargs']['userrole']
					if 'driver' in userrole:
						driverid = self.scope['url_route']['kwargs']['userid']
						driver_obj = DriverModel.objects.filter(id  = driverid).first()
						if driver_obj:
							drivercoordinates_obj = DriverCoordinates.objects.filter(driver = driver_obj).first()
							if drivercoordinates_obj:
								drivercoordinates_obj.latitude = latitude_val
								drivercoordinates_obj.longitude = longitude_val
								drivercoordinates_obj.save()
								print('coordinates updated')
							else:
								DriverCoordinates.objects.create(user_id = driver_obj.user.id, driver = driver_obj, latitude = latitude_val, longitude = longitude_val)
								print('coordinates obj created')
							# return JsonResponse({'status_code': 200, 'status_message': 'success',})
						else:
							pass
							# return JsonResponse({'status_code': 400, 'status_message': 'User not logged in'})
				
				except Exception as e:
					print('driver get coordinates')

					driverid = self.scope['url_route']['kwargs']['userid']
					driver_obj = DriverModel.objects.filter(id  = driverid).first()
					if driver_obj:
						customerjobid_val = b['customerjobid']
						parcelpicked = False
						driverjob_obj = DriverJob.objects.filter(customerjob_id = customerjobid_val).first()
						if driverjob_obj:
							if driverjob_obj.jobstarted:
								parcelpicked = True
						drivercoordinates_obj = DriverCoordinates.objects.filter(driver = driver_obj).first()
						if drivercoordinates_obj:
							drivercoordinates_data = {}
						
							drivercoordinates_data.update({
								'driverid': driver_obj.id,
								'latitude': drivercoordinates_obj.latitude,
								'longitude': drivercoordinates_obj.longitude,
								'parcelpicked': parcelpicked,
								})
							print(drivercoordinates_data)
							# if 'driver' in self.group_name:
							# 	othergroup_name = 'admin_1'
							# else:
							# 	othergroup_name = 'driver' + '_' +str(drivercoordinates_data['driverid'])
							await self.channel_layer.group_send(
								self.group_name,
								{
									"type":"new_message",
									"text":json.dumps(drivercoordinates_data)
								}
							)
				
		except Exception as e:
			print(e)			

		# await self.send(text_data="Hello world!")
		
	async def websocket_disconnect(self, close_code):
		print('\n'*4)
		print('in DriverCoordinatesConsumer - disconnect')
		print('\n'*4)
		# Called when the socket closes
		userid = self.scope['url_route']['kwargs']['userid']

		await self.channel_layer.group_discard(
			'driver_'+ str(userid),
			self.channel_name
			)
		try:
			raise StopConsumer() # this one deals with warnings
		except Exception as e:
			print(e)





class ChatConsumer(AsyncConsumer):
	groups = ["broadcast"]

	async def websocket_connect(self, event):
		print('\n'*4)
		print('in ChatConsumer - connect')
		print('\n'*4)
		
		userrole = self.scope['url_route']['kwargs']['userrole']
		userid = self.scope['url_route']['kwargs']['userid']
		self.group_name = str(userrole) + '_' + str(userid)
		print('group_name = ', self.group_name)

		await self.channel_layer.group_add(
	        self.group_name,
	        self.channel_name
        )
		
		await self.send({
			'type':'websocket.accept'
			})
		
	async def new_message(self,event):
		print('\n'*10)
		print(' notification newww \n\n\n')
		print(event)
		print('\n'*10)
		try:
			await self.send({
				"type":"websocket.send",
				"text":event['text']
			})
			st = json.loads(event['text'])
			print(st['sender'])
			if st['sender'] == 'admin':
				print('0')
				driver_obj = DriverModel.objects.filter(id = st['driverid']).first()
				print('1')
				if driver_obj:
					print('2')
					try:
						print('3')
						sendfcmnotification(driver_obj.fcmtoken, 'driver', 'newmessage', 'Admin Message', st['message'])
						print('4')
					except Exception as e:
						print(e)
						print('5')
				
		except Exception as e:
			print(e)
			pass

	# @database_sync_to_async
	async def websocket_receive(self, event):
		# Called with either text_data or bytes_data for each frame
		print('\n'*4)
		print('in ChatConsumer - receive')
		print(event)
		print('\n'*4)
		print(event['text'])
		# print(type(event['text']))
		print('\n'*4)
		print('0'*19)
		if event['text'] == 'update client':
			try:	
				# driverid = self.scope['url_route']['kwargs']['driverid']
				pass
			except Exception as e:
				driverid = 5
			# driverid = 5
			chat_obj = Chat.objects.filter(driver_id = driverid).last()
			if chat_obj:
				latest_message_data = []
				if chat_obj.files:
					attachment = str(settings.WEB_BASE_URL) + chat_obj.files.name
				else:
					attachment = ''
				latest_message_data.append({
					'adminid': chat_obj.admin.id,
					'adminname': chat_obj.admin.name,
					'driverid': chat_obj.driver.id,
					'drivername': chat_obj.driver.name,
					'message':chat_obj.message,
					'sender': chat_obj.sender,
					'attachment': attachment,
					'time' : chat_obj.created_at.strftime("%d/%m/%Y %I:%M:%S %p"),
					})
				print(latest_message_data)
				await self.send({
					"type":"websocket.send",
					"text":json.dumps(latest_message_data)
				})			
			
		elif event['text'] == 'test':
			pass
		else:
			b = json.loads(event['text'])
			# print(b)
			# for b in a:
			try:
				# print(b)
				# print(type(b))
				sender = b['sender']
				driver_id = b['driver_id']
				messageexist = b['messageexist']
				message = b['message']
				attachmentexist = b['attachmentexist']
				print(sender)
				print(driver_id)
				print(messageexist)
				print(message)
				print(attachmentexist)
				if messageexist == 'yes':
					message = b['message']
				if attachmentexist == 'yes':
					# attachment = request.FILES['file']
					attachment = b['file']
					if attachment:
						print('attachment exists')
					else:
						print('no attachment')
				admin_id = 1
				if driver_id and admin_id  and sender:
					if messageexist == 'yes':
						chat_obj = Chat.objects.create(driver_id = driver_id, admin_id = admin_id, message = message, sender = sender)
						if chat_obj:
							print('message saved in database')
					if attachmentexist == 'yes':
						st = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(8)])
						print(st)
						fs = FileSystemStorage()
						filename = fs.save(attachment.name, attachment)
						filename = fs.url(filename)
						filename = '/media/' + filename 
						print(filename)
						chat_obj = Chat.objects.create(driver_id=driver_id,admin_id=admin_id,files=filename,sender=sender)
						if chat_obj:
							print('attachment saved in database')		

					try:
						foradmin, fordriver = False, False
						if sender == 'driver':
							foradmin = True
							sendername = chat_obj.driver.name
							user_id = chat_obj.admin.user.id
						else:
							fordriver = True
							sendername = 'Admin'
							user_id = chat_obj.driver.user.id
						Notifications.objects.create( user_id = user_id, foradmin = foradmin, fordriver = fordriver, notificationtype = 'New Message', notificationtext = 'New message from ' + sendername + '.' , status = 'unread')
					except Exception as e:
						print(e)
					latest_message_data = {}
					# driverid = self.scope['url_route']['kwargs']['driverid']
					chat_obj = Chat.objects.filter(driver_id = driver_id, admin_id = admin_id).last()
					if chat_obj:
						if chat_obj.files:
							attachment = str(settings.WEB_BASE_URL) + chat_obj.files.name
						else:
							attachment = ''
						latest_message_data.update({
							'adminid': chat_obj.admin.id,
							'adminname': chat_obj.admin.name,
							'driverid': chat_obj.driver.id,
							'drivername': chat_obj.driver.name,
							'message':chat_obj.message,
							'sender': chat_obj.sender,
							'attachment': attachment,
							'time' : chat_obj.created_at.strftime("%d/%m/%Y %I:%M:%S %p"),
							})
						print(latest_message_data)
						
						if 'driver' in self.group_name:
							othergroup_name = 'admin_1'
						else:
							othergroup_name = 'driver' + '_' +str(latest_message_data['driverid'])
						await self.channel_layer.group_send(
							self.group_name,
							{
								"type":"new_message",
								"text":json.dumps(latest_message_data)
							}
						)
						await self.channel_layer.group_send(
							othergroup_name,
							{
								"type":"new_message",
								"text":json.dumps(latest_message_data)
							}
						)


				print('success')
				
			except Exception as e:
				print(e)

			# print(b['message'])
		# You can call:
		
		# driverid = self.scope['url_route']['kwargs']['driverid']
		# chat_data= [] 
		# chat_obj = Chat.objects.filter(driver_id = driverid).order_by('created_at')
		# if chat_obj:
		# 	for chat in chat_obj:
		# 		chat_data.append({
		# 			'adminid': chat.admin.id,
		# 			'adminname': chat.admin.name,
		# 			'driverid': chat.driver.id,
		# 			'drivername': chat.driver.name,
		# 			'message':chat.message,
		# 			})
		# await self.send({
		# 		"type":"websocket.send",
		# 		"text":json.dumps(chat_data)
		# 	})			

		# await self.send(text_data="Hello world!")
	

	
	async def disconnect(self, close_code):
		print('\n'*4)
		print('in ChatConsumer - disconnect')
		print('\n'*4)
		await self.channel_layer.group_discard(
			'admin_1',
			self.channel_name
			)
		try:
			raise StopConsumer() # this one deals with warnings
		except Exception as e:
			print(e)


	# await database_sync_to_async	
	# async def websocket_disconnect(self, close_code):
	# 	print('\n'*4)
	# 	print('in ChatConsumer - disconnect')
	# 	print('\n'*4)
	# 	await self.channel_layer.group_discard(
	# 		'admin_1',
	# 		self.channel_name
	# 		)
	# 	try:
	# 		raise StopConsumer() # this one deals with warnings
	# 	except Exception as e:
	# 		print(e)
		# Called when the socket closes












class AdminChatConsumer(AsyncConsumer):
	groups = ["broadcast"]

	async def websocket_connect(self, event):
		print('\n'*4)
		print('in AdminChatConsumer - connect')
		print('\n'*4)
		
		# self.group_name = 'admin'
		# print('group_name = ', self.group_name)

		# await self.channel_layer.group_add(
	 #        self.group_name,
	 #        self.channel_name
  #       )
		# myResponse = {
		# 'message':"event['text']"
		# }
		
		await self.send({
			'type':'websocket.accept'
			})

	async def new_message(self,event):
		print('\n'*10)
		print(' admin - sockets \n\n\n')
		print(event)
		print('\n'*10)
		try:
			await self.send({
				"type":"websocket.send",
				"text":event['text']
			})
				
		except Exception as e:
			print(e)
			pass

	async def websocket_receive(self, event):
		# Called with either text_data or bytes_data for each frame
		print('\n'*4)
		print('in AdminChatConsumer - receive')
		print(event)
		print('\n'*4)
		print(event['text'])
		# print(type(event['text']))
		print('\n'*4)
		if event['text'] == 'update client':
			driverid = self.scope['url_route']['kwargs']['driverid']
			chat_obj = Chat.objects.filter(driver_id = driverid).last()
			if chat_obj:
				latest_message_data = []
				if chat_obj.files:
					attachment = str(settings.WEB_BASE_URL) + chat_obj.files.name
				else:
					attachment = ''
				latest_message_data.append({
					'adminid': chat_obj.admin.id,
					'adminname': chat_obj.admin.name,
					'driverid': chat_obj.driver.id,
					'drivername': chat_obj.driver.name,
					'message':chat_obj.message,
					'sender': chat_obj.sender,
					'attachment': attachment,
					'time' : chat_obj.created_at.strftime("%d/%m/%Y %I:%M:%S %p"),
					})
				print(latest_message_data)
				await self.send({
					"type":"websocket.send",
					"text":json.dumps(latest_message_data)
				})			
			
		elif event['text'] == 'test':
			pass
		else:
			b = json.loads(event['text'])
			print(b)
			# for b in a:
			try:
				print(b)
				# print(type(b))
				sender = b['sender']
				if sender == 'driver':
					await self.channel_layer.group_send(
							self.group_name,
							{
								"type":"new_message",
								"text":event['text']
							}
						)
				else:
					driver_id = b['driver_id']
					messageexist = b['messageexist']
					message = b['message']
					attachmentexist = b['attachmentexist']
					print(sender)
					print(driver_id)
					print(messageexist)
					print(message)
					print(attachmentexist)
					if messageexist == 'yes':
						message = b['message']
					if attachmentexist == 'yes':
						# attachment = request.FILES['file']
						attachment = b['file']
						if attachment:
							print('attachment exists')
						else:
							print('no attachment')
					admin_id = 1
					if driver_id and admin_id  and sender:
						if messageexist == 'yes':
							chat_obj = Chat.objects.create(driver_id=driver_id,admin_id=admin_id,message=message,sender=sender)
							if chat_obj:
								print('message saved in database')
						if attachmentexist == 'yes':
							st = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(8)])
							print(st)
							fs = FileSystemStorage()
							filename = fs.save(attachment.name, attachment)
							filename = fs.url(filename)
							filename = '/media/' + filename 
							print(filename)
							chat_obj = Chat.objects.create(driver_id=driver_id,admin_id=admin_id,files=filename,sender=sender)
							if chat_obj:
								print('attachment saved in database')		

						latest_message_data = {}
						driverid = self.scope['url_route']['kwargs']['driverid']
						chat_obj = Chat.objects.filter(driver_id = driverid).last()
						if chat_obj:
							if chat_obj.files:
								attachment = str(settings.WEB_BASE_URL) + chat_obj.files.name
							else:
								attachment = ''
							latest_message_data.update({
								'adminid': chat_obj.admin.id,
								'adminname': chat_obj.admin.name,
								'driverid': chat_obj.driver.id,
								'drivername': chat_obj.driver.name,
								'message':chat_obj.message,
								'sender': chat_obj.sender,
								'attachment': attachment,
								'time' : chat_obj.created_at.strftime("%d/%m/%Y %I:%M:%S %p"),
								})
							print(latest_message_data)
							
							
							await self.channel_layer.group_send(
								self.group_name,
								{
									"type":"new_message",
									"text":json.dumps(latest_message_data)
								}
							)
							
					print('success')
				
			except Exception as e:
				print(e)

			# print(b['message'])
		
	async def websocket_disconnect(self, close_code):
		print('\n'*4)
		print('in AdminChatConsumer - disconnect')
		print('\n'*4)
		# Called when the socket closes








class DriverUpdateCoordinates(AsyncConsumer):
	groups = ["broadcast"]

	async def websocket_connect(self, event):
		print('\n'*4)
		print('in AdminChatConsumer - connect')
		print('\n'*4)
		
		
		await self.send({
			'type':'websocket.accept'
			})
		# await self.send({
		# 		"type":"websocket.send",
		# 		"text":json.dumps({'hello':1})
		# 	})

	async def websocket_receive(self, event):
		# Called with either text_data or bytes_data for each frame
		print('\n'*4)
		print('in AdminChatConsumer - receive')
		print('\n'*4)
		print(event['text'])
		# You can call:
		adminid = 1
		driverid = 1
		chat_data= [] 
		chat_obj = Chat.objects.filter(admin_id = adminid, driver_id = driverid).order_by('created_at')
		if chat_obj:
			for chat in chat_obj:
				chat_data.append({
					'adminid': chat.admin.id,
					'adminname': chat.admin.name,
					'driverid': chat.driver.id,
					'drivername': chat.driver.name,
					'message':chat.message,
					})
		await self.send({
				"type":"websocket.send",
				"text":json.dumps(chat_data)
			})			

		# await self.send(text_data="Hello world!")
		
	async def websocket_disconnect(self, close_code):
		print('\n'*4)
		print('in AdminChatConsumer - disconnect')
		print('\n'*4)
		# Called when the socket closes


class DriverGetChats(AsyncConsumer):
	groups = ["broadcast"]

	async def websocket_connect(self, event):
		print('\n'*4)
		print('in DriverGetChats - connect')
		print('\n'*4)
		
		driverid = self.scope['url_route']['kwargs']['driverid']
		self.group_name = str(driverid)
		print('group_name = ', self.group_name)

		await self.channel_layer.group_add(
	        self.group_name,
	        self.channel_name
        )
		# myResponse = {
		# 'message':"event['text']"
		# }
		
		await self.send({
			'type':'websocket.accept'
			})
		
	async def new_message(self,event):
		print('\n'*10)
		print(' notification newwwwwwwwwwwwwwwwwwwwwwww \n\n\n')
		print(event)
		print('\n'*10)
		try:
			await self.send({
				"type":"websocket.send",
				"text":event['text']
			})
			st = json.loads(event['text'])
			print(st['sender'])
			if st['sender'] == 'admin':
				print('0')
				driver_obj = DriverModel.objects.filter(id = st['driverid']).first()
				print('1')
				if driver_obj:
					print('2')
					try:
						print('3')
						sendfcmnotification(driver_obj.fcmtoken, 'driver', 'newmessage', 'Admin Message', st['message'])
						print('4')
					except Exception as e:
						print(e)
						print('5')
				
		except Exception as e:
			print(e)
			pass


	async def websocket_receive(self, event):
		# Called with either text_data or bytes_data for each frame
		print('\n'*4)
		print('in DriverGetChats - receive')
		print(event)
		print('\n'*4)
		print(event['text'])
		# print(type(event['text']))
		print('\n'*4)
		if event['text'] == 'update client':
			driverid = self.scope['url_route']['kwargs']['driverid']
			chat_obj = Chat.objects.filter(driver_id = driverid).last()
			if chat_obj:
				latest_message_data = []
				if chat_obj.files:
					attachment = str(settings.WEB_BASE_URL) + chat_obj.files.name
				else:
					attachment = ''
				latest_message_data.append({
					'adminid': chat_obj.admin.id,
					'adminname': chat_obj.admin.name,
					'driverid': chat_obj.driver.id,
					'drivername': chat_obj.driver.name,
					'message':chat_obj.message,
					'sender': chat_obj.sender,
					'attachment': attachment,
					'time' : chat_obj.created_at.strftime("%d/%m/%Y %I:%M:%S %p"),
					})
				print(latest_message_data)
				await self.send({
					"type":"websocket.send",
					"text":json.dumps(latest_message_data)
				})			
			
		elif event['text'] == 'test':
			pass
		else:
			b = json.loads(event['text'])
			print(b)
			# for b in a:
			try:
				print(b)
				# print(type(b))
				sender = b['sender']
				driver_id = b['driver_id']
				messageexist = b['messageexist']
				message = b['message']
				attachmentexist = b['attachmentexist']
				print(sender)
				print(driver_id)
				print(messageexist)
				print(message)
				print(attachmentexist)
				if messageexist == 'yes':
					message = b['message']
				if attachmentexist == 'yes':
					# attachment = request.FILES['file']
					attachment = b['file']
					if attachment:
						print('attachment exists')
					else:
						print('no attachment')
				admin_id = 1
				if driver_id and admin_id  and sender:
					if messageexist == 'yes':
						chat_obj = Chat.objects.create(driver_id=driver_id,admin_id=admin_id,message=message,sender=sender)
						if chat_obj:
							print('message saved in database')
					if attachmentexist == 'yes':
						st = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(8)])
						print(st)
						fs = FileSystemStorage()
						filename = fs.save(attachment.name, attachment)
						filename = fs.url(filename)
						filename = '/media/' + filename 
						print(filename)
						chat_obj = Chat.objects.create(driver_id=driver_id,admin_id=admin_id,files=filename,sender=sender)
						if chat_obj:
							print('attachment saved in database')		

					latest_message_data = {}
					driverid = self.scope['url_route']['kwargs']['driverid']
					chat_obj = Chat.objects.filter(driver_id = driverid).last()
					if chat_obj:
						if chat_obj.files:
							attachment = str(settings.WEB_BASE_URL) + chat_obj.files.name
						else:
							attachment = ''
						latest_message_data.update({
							'adminid': chat_obj.admin.id,
							'adminname': chat_obj.admin.name,
							'driverid': chat_obj.driver.id,
							'drivername': chat_obj.driver.name,
							'message':chat_obj.message,
							'sender': chat_obj.sender,
							'attachment': attachment,
							'time' : chat_obj.created_at.strftime("%d/%m/%Y %I:%M:%S %p"),
							})
						print(latest_message_data)
						
						
						await self.channel_layer.group_send(
							self.group_name,
							{
								"type":"new_message",
								"text":json.dumps(latest_message_data)
							}
						)
						#below code is to hit admin web socket
						# try:
						# 	import websocket
						# 	import time
						# 	try:
						# 		import thread
						# 	except ImportError:
						# 		import _thread as thread

						# 	ws = websocket.WebSocket()
						# 	socket_creation_response = ws.connect("ws://kwickdelivery.co.uk:9090/chat/admin/")
						# 	print(socket_creation_response)
						# 	def on_message(ws, message):
						# 		print(message)

						# 	def on_error(ws, error):
						# 		print(error)

						# 	def on_close(ws):
						# 		print("### closed ###")

						# 	def on_open(ws):
						# 		print("open")
						# 		# def run(*args):
						# 		# 	for i in range(3):
						# 		# 		time.sleep(1)
						# 		# 		ws.send("Hello %d" % i)
						# 		# 	time.sleep(1)
						# 		# 	ws.close()
						# 		# 	print("thread terminating...")
						# 		# thread.start_new_thread(run, ())
						# 	ws.send(json.dumps(latest_message_data))
						# except Exception as e:
						# 	print(e)	



				print('success')
				
			except Exception as e:
				print(e)

			# print(b['message'])
		# You can call:
		
		# driverid = self.scope['url_route']['kwargs']['driverid']
		# chat_data= [] 
		# chat_obj = Chat.objects.filter(driver_id = driverid).order_by('created_at')
		# if chat_obj:
		# 	for chat in chat_obj:
		# 		chat_data.append({
		# 			'adminid': chat.admin.id,
		# 			'adminname': chat.admin.name,
		# 			'driverid': chat.driver.id,
		# 			'drivername': chat.driver.name,
		# 			'message':chat.message,
		# 			})
		# await self.send({
		# 		"type":"websocket.send",
		# 		"text":json.dumps(chat_data)
		# 	})			

		# await self.send(text_data="Hello world!")
		
	async def websocket_disconnect(self, close_code):
		print('\n'*4)
		print('in DriverGetChats - disconnect')
		print('\n'*4)
		# Called when the socket closes




